C++: How do I access a variable from another class definition [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
I'm trying to make a little pokemon game, that obviously includes attacking another pokemon. Don't worry about Type; that's just a ENUM.
Currently not working: The _reciever's health doesn't get changed, there are no errors
my current not working code:
class Pokemon
{
public:
string Name;
Type Type;
int Health;
Pokemon(string _name, Pokemons::Type _type, int _health)
{
Name = _name;
Type = _type;
Health = _health;
}
bool checkHealth()
{
if (Health <= 0)
{
return false;
}
return true;
}
void updateHealth(char _operator, int _amount)
{
switch (_operator)
{
case '+':
Health = Health + _amount;
break;
case '-':
Health = Health - _amount;
break;
case '*':
Health = Health * _amount;
break;
case '/':
Health = Health / _amount;
break;
}
}
void attackEnemy(Pokemon _reciever)
{
_reciever.Health = _reciever.Health - 5;
}
};
#include <iostream>
#include "Pokemon.h"
using namespace std;
using namespace Pokemons;
int main()
{
Pokemon Charmender("Charmender", Fire, 45);
Pokemon Bulbasaur("Bulbasaur", Water, 50);
while (true) {
Charmender.attackEnemy(Bulbasaur);
cout << Bulbasaur.Health << endl;
}
}
ps: this is my first ever stackoverflow question, do let me know if I missed something

Currently, you are accessing the other class member variables without problems, but your changes are not as intended because you are passing a copy of the object:
void attackEnemy(Pokemon _reciever)
{
_reciever.Health = _reciever.Health - 5;
}
With this approach, _receiver goes away at the end of your method.
To get persistent changes, you can pass by reference:
void attackEnemy(Pokemon &_reciever)
{
_reciever.Health = _reciever.Health - 5;
}

Related

No Matching Function To Call Error, and i don't know why [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
Improve this question
I'm having an error that the function that I'm calling doesn't exist and I don't know why. It seems to have something to do with pointers but we haven't learned pointers. I call the function and wrote it and declared it (I'm mostly just typing so I can post this at this point)
Here is my code
/*
* Program to validate a color and show its index
*
* Name: Rebecca Sakson
* Date: November 13, 2022
*/
#include <iostream>
using namespace std;
const int NUM_COLORS = 5;
int findColorIndex (string findMe, string list[], int index[]);
int main()
{
string colors[NUM_COLORS] = { "red", "green", "blue", "yellow", "purple"};
int index[NUM_COLORS] = {0,1,2,3,4};
string findMe;
int colorIndex;
//int idkWhy = NUM_COLORS;
cout << "Color?" << endl;
cin >> findMe;
colorIndex = findColorIndex(findMe, colors, NUM_COLORS);
if (colorIndex <= 0)
{
cout << "Color is valid, found at " << colorIndex << endl;
}
else
{
cout << findMe << " is not valid";
}
return 0;
}
int findColorIndex (string findColor, string list[], int index[])
{
bool found = false;
int functionIndex = 0;
while ((!found) && (functionIndex < *index))
{
if (list[functionIndex] == findColor)
{
found = true;
}
else
{
functionIndex++;
}
}
if (!found)
{
functionIndex = -1;
}
return functionIndex;
}
I think you meant to type this:
findColorIndex(findMe, colors, index);
Instead of passing NUM_COLORS, which is an int, not an int array.

C++, return array from function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Im building this subnet calculator but now im stuck, with array. I want to create new int function that will return array, but I don't know how I tried many things but still don't have idea, think it will have to do something with pointers. I want to create new function starting at "while(octet4>0)". so octet4 gets passed into function and function should return fully functional array which I can use then in main. Hope somebody will know answer for what im looking for, hope solution would not be too complicated because Im just learning programming and thought this would be fun project to take on.
int main() {
int i=0,j,q,s,size=8,temp;
int binary_ip[8];
int netmask;
int mask;
int octet1, octet2, octet3, octet4;
string ip;
cout<<"Vnesite IP naslov, npr. 192.168.32.55:"<<endl;
cin>>ip;
cout<<"Vnesite netmasko, npr. /27:"<<endl;
cin>>netmask;
stringstream stream(ip);
char ch;
stream >> octet1 >> ch >> octet2 >> ch >> octet3 >> ch >> octet4;
while(octet4>0){
binary_ip[i]=octet4%2;
i++;
octet4=octet4/2;
}
switch(i){
case 7:binary_ip[7]=0;
break;
case 6:for(s=6;s<=7;s++)binary_ip[s]=0;
break;
case 5:for(s=5;s<=7;s++)binary_ip[s]=0;
break;
case 4:for(s=4;s<=7;s++)binary_ip[s]=0;
break;
case 3:for(s=3;s<=7;s++)binary_ip[s]=0;
break;
case 2:for(s=2;s<=7;s++)binary_ip[s]=0;
break;
case 1:for(s=1;s<=7;s++)binary_ip[s]=0;
break;
}
for(q=0;q<size/2;q++){
temp=binary_ip[size-1-q];
binary_ip[size-1-q]=binary_ip[q];
binary_ip[q]=temp;}
return 0;
}
Some options:
Use std::array instead of a regular C array. Those are easier to work with and you are already using standard library. http://www.learncpp.com/cpp-tutorial/6-15-an-introduction-to-stdarray/
Have your function fill-in the array, rather than create and return it:
void MakeArray(int octet4, int binary_ip[8]) ;
Use pointers, allocate array with "new" and free it with "delete". You'll need a way to know the size of the array, however.
#include <iostream>
int array(int octet4, int binary_ip[]);
int main()
{
int binary_ip[6];
int octet4 = 55;
int i = 0;
i = array(octet4, binary_ip);//binary_ip passes in the address of the first element in the array
}
int array(int octet4, int binary_ip[])
{
int i = 0;
while(octet4>0)
{
binary_ip[i]=octet4%2;
i++;
octet4=octet4/2;
}
return i;
}
or you can use a vector like Daniel H suggested
void array(int octet4, std::vector<int> &binary_ip)
{
while(octet4>0)
{
binary_ip.push_back(octet4%2);
octet4=octet4/2;
}
}
int main()
{
std::vector<int> binary_ip;
int octet4 = 55;
array(octet4, binary_ip);
}

Pointer to pointer not work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In my code I am trying to make loop that works by changing pointer target and printing value of the same pointer. This code is my method for infinite list.
#include <iostream>
using namespace std;
class pacjent
{
public:
char nazwisko[20];
pacjent*nastepny;
pacjent();
~pacjent();
};
pacjent *POCZATEK = NULL, *KONIEC = NULL;
pacjent::pacjent() {
cout << "Podaj nazwisko: ";
cin >> nazwisko;
if (POCZATEK == NULL) {
POCZATEK = this;
KONIEC = this;
} else {
KONIEC->nastepny = this;
nastepny = NULL;
}
}
pacjent::~pacjent() {
POCZATEK = POCZATEK->nastepny;
}
pacjent* NOW = POCZATEK;
void drukuj() {
///////////////////////////////// LOOP MENTIONED
// while(NOW->nastepny!=NULL)
// {
cout << NOW->nazwisko << endl; //do not work
// NOW=NOW->nastepny;
// cout << POCZATEK->nazwisko << endl; // works fine
// }
} //////////////////////////////////
int main() {
char SELECTOR;
while (SELECTOR != 'q') {
cin >> SELECTOR;
switch (SELECTOR) {
case 'n':
KONIEC = new pacjent;
break;
case 'p':
delete POCZATEK;
break;
case 'd':
drukuj();
break;
default:
break;
}
}
return 0;
}
The function drukuj() won't print content of 'NOW' (I get empty screen) pointer but with POCZATEK works fine. Any ideas?
The function drukuj() won't print content of 'NOW' (I get empty screen) pointer but with POCZATEK works fine. Any ideas?
NOW is initialized as:
pacjent* NOW = POCZATEK;
At that time, the value of POCZATEK is NULL. Hence, NOW also gets initialized to NULL. Later on in your code, POCZATEK is changed to point to newly created objects but that does not change where NOW points to. It still points to NULL.
You can make sure NOW and POCZATEK always point to the same object by making NOW a reference to a pointer and initialize it with POCZATEK.
pacjent*& NOW = POCZATEK;
pacjent* NOW = POCZATEK; // this is null
Create new pacjent object and assign it's members the values you want then try to print out.

Errors with Unsorted List? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So I have a homework assignment due tonight and I'm trying to compile it to test but I'm running into a bunch of errors and some of them seem to make zero sense? The errors mention things like: "syntax error before '::'" and the like, but I have never encountered errors like these and have 0 idea on how to fix them.
UnsortedClass.cpp
#include "UnsortedClass.h"
void UnsortedType::UnsortedType()
{
length = 0;
}
bool UnsortedType::IsFull() const
{
return (length == MAX_ITEMS);
}
int UnsortedType::GetLength() const
{
return length;
}
NBA UnsortedType::GetItem(NBA customPlayer, bool& found)
{
bool moreToSearch;
int location = 0;
found = false;
moreToSearch = (location < length);
while (moreToSearch && !found)
{
switch (customPlayer.ComparedTo(info[location]))
{
case LESS :
case GREATER : location++;
moreToSearch = (location < length);
break;
case EQUAL : found = true;
item = info[location];
break;
}
}
return customPlayer;
}
void UnsortedType::MakeEmpty()
{
length = 0;
}
void UnsortedType::PutItem(NBA customPlayer)
{
info[length] = customPlayer;
length++;
}
void UnsortedType::DeleteItem(NBA customPlayer)
{
int location = 0;
while (customPlayer.ComparedTo(info[location]) != EQUAL)
location++;
info[location] = info[length - 1];
length--;
}
void UnsortedType::ResetList()
{
currentPos = -1;
}
NBA UnsortedType::GetNextItem()
{
currentPos++;
return info[currentPos];
}
UnsortedClass.h
#include "NBA.h"
class UnsortedClass //declares a class data type
{
public:
// 8 public member functions
void UnsortedType ( );
bool IsFull () const; //checks if list is full
int GetLength () const ; // returns length of list
NBA GetItem (NBA customPlayer, bool& found); //gets item specified in parameters
void PutItem (NBA customPlayer); //puts NBA player in list
void DeleteItem (NBA customPlayer); //deletes NBA player from list
void ResetList (); //resets list to 0
NBA GetNextItem (); //gets next item after current list position
private:
// 3 private data members
int length;
NBA info[MAX_ITEMS];
int currentPos;
};
NBA.h
#include <string>
using namespace std;
const int MAX_ITEMS = 10;
enum RelationType {LESS, GREATER, EQUAL};
class NBA {
private:
char firstInitial;
string lastName;
string team;
char position;
public:
void set_first_initial(char playerFirstInitial);
void set_last_name(string playerLastName);
void set_team(string teamName);
void set_position(char position);
char get_first_initial();
string get_last_name();
string get_team();
char get_position();
};
The errors I've been receiving are as follows (in picture format as I can't paste the lines without Stackoverflow interpreting it as code)
Constructors don't have a return type specified. Change
void UnsortedType::UnsortedType()
to
UnsortedType::UnsortedType()
Also the class name in its header declaration is wrong; everywhere else says UnsortedType but this says:
class UnsortedClass //declares a class data type

Beginning of an nQueens game in c++. Where is the error located in my code? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I keep getting errors when trying to compile the following code. The error is
expected ',' or ';' before '{' token.
It says there's an error on the parentheses after the bool check_row(x)
If I comment it out the same happens for bool check_col(x).
I kept looking back at my books if I didn't define my functions properly but they seem correct, logically.
This is the beginning of an nQueens game on a 4x4 board.
The Queen is represented by the number 1.
The two boolean functions are to check if the row and columns are free.
startGame() assigns 0 to all boxes, and showBoard() shows results of the board.
#include <cstdlib>
#include <iostream>
using namespace std;
int x=0, y=0;
int square[4][4];
void startGame()
{
for(x=0;x<4;x++)
{
for(y=0;y<4;y++)
{
square[x][y]=0;
}
}
}
void showBoard()
{
for(int x=0;x<4;x++)
{
if(x!=0)
{
cout<<endl;
}
for(int y=0;y<4;y++)
{
cout<<square[x][y];
}
}
cout<<endl;
}
bool check_row(x)
{
for(y=0;y<4;y++)
{
if(square[x][y]==1)
{
return false;
}
else if(square[x][y]==0)
{
if(y==3)
{
return true;
}
continue;
}
}
}
bool check_col(y)
{
for(int x=0;x<4;x++)
{
if(square[x][y]==1)
{
return false;
}
else if(square[x][y]==0)
{
if(x==3)
{
return true;
}
continue;
}
}
}
int main(){
startGame();
showBoard();
return 0;
}
bool check_col(y) isn't a valid prototype. You need to provide a type for y - for example bool check_col(int y). The same applies to bool check_row(x).
you have to specify the datatype which you are passing as a parameter in your function..considering x and y are of int type and are local, your function prototype should be
bool check_row(int x)
bool check_col(int y)
If x and y are global then there is no need to pass them..simply
bool check_row()
bool check_col()
will work as the visibility of global variables will be throughout the program, unless shadowed