Issues with array in header file C++ - c++

I am trying to create a player object that has its own array of Territories but whenever I compile these errors appear :
Player.cpp(15,4): error C2065: 'playerTerritories': undeclared identifier
Player.cpp(27,11): error C2065: 'playerTerritories': undeclared identifier
Player.h(15,29): error C3646: 'playerTerritories': unknown override specifier
Player.h(15,29): error C2143: syntax error: missing ',' before '['
Player.h(15,32): error C2143: syntax error: missing ')' before ';'
Player.h(15,32): error C2238: unexpected token(s) preceding ';'
I have tried moving the array to the cpp file but then the array becomes undefined in the toDefend method.
This is how my cpp file looks so far:
#include "Player.h"
#include <iostream>
using std::cout;
//Arrays for territories to choose from
extern std::string territoriesArr[] = { "Alaska","North West Territories", "Quebec", "Alberta", "Ontario", "Eastern US", "Western US", "Mexico", "Venezuela", "Peru", "Brazil", "Argentina" };
//The territories of our enemy
extern std::string enemy_territoriesArr[] = { "Great Britain", "Iceland", "Northern Europe", "Western Europe", "Southern Europe", "Scandanavia" };
//The array of cards that we can draw
extern std::string cardTypeArr[] = { "bomb", "reinforcement", "blockade", "airlift", "diplomacy" };
Player::Player() {
//Randomly choose territories and place into our playerTerritories array, we dont care about dupilcates for now
for (int i = 0; i < 6; i++) {
int r = rand() % 12;
playerTerritories[i] = Territory(territoriesArr[r]);
}
//Randomly choose cards and place into our card array
for (int i = 0; i < 3; i++) {
int r = rand() % 5;
playerHand[i] = Card(cardTypeArr[r]);
}
}
//Method to print out all the territories of a player
void Player::toDefend() {
cout << "Territories to defend: ";
for (int i = 0; i < 6; i++) {
cout << playerTerritories[i].getTerritoryName() << std::endl;
}
}
//Method to print out all the enemy territories
void Player::toAttack() {
cout << "Territories to attack";
for (std::string x : enemy_territoriesArr) {
cout << x << std::endl;
}
}
void Player::getPlayerHand() {
cout << "Cards in hand";
for (Card x : playerHand) {
cout << x.getCardName() << std::endl;
}
}
and my h file looks like
#ifndef PLAYER_H
#define PLAYER_H
#include <string>
class Player {
public:
Player();
void toDefend();
void toAttack();
//void issueOrder(std::string order); TODO latter
void getPlayerHand();
//void getOrderList(); TODO latter
private:
Territory playerTerritories[6];
Card playerHand[3];
};
class Territory {
public:
Territory();
Territory(std::string name);
std::string getTerritoryName();
private:
std::string territoryName;
};
class Card{
public:
Card();
Card(std::string type);
std::string getCardName();
private:
std::string cardType;
};
class Order {
public:
Order(std::string name);
private:
std::string orderName;
};
#endif
Help would be much appreciated

In your header file, move class Territory { and class Card{ declarations above class Player {, as it is using them.

Related

Implementing Observer design

I was trying Observer Pattern with some basic implementation using C++. But I got these errors:
Error C2065 'mod': undeclared identifier obs_example C:\Users\silae\source\repos\obs_example\Obs.h 9
Error C2065 'model': undeclared identifier obs_example C:\Users\silae\source\repos\obs_example\Obs.h 9
Error C2065 'model': undeclared identifier obs_example C:\Users\silae\source\repos\obs_example\Obs.h 11
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int obs_example C:\Users\silae\source\repos\obs_example\Obs.h 6
Error C2061 syntax error: identifier 'Subject' obs_example C:\Users\silae\source\repos\obs_example\Obs.h 8
Error C2143 syntax error: missing ';' before '*' obs_example C:\Users\silae\source\repos\obs_example\Obs.h 6
Error C2238 unexpected token(s) preceding ';' obs_example C:\Users\silae\source\repos\obs_example\Obs.h 6
These are my files:
Obs.h
#pragma once
#include "Subject.h"
class Observer
{
Subject* model;
public:
Observer(Subject* mod) {
model = mod;
model->attach(this);
}
virtual void update() = 0;
};
Subject.h
#pragma once
#include <vector>
#include "Obs.h"
class Subject
{
std::vector < class Observer* > views; // 3. Coupled only to "interface"
public:
void attach(Observer *obs) {
views.push_back(obs);
}
void notify();
};
void Subject::notify() {
for (int i = 0; i < views.size(); i++)
views[i]->update();
}
Class.h
#pragma once
#include "Obs.h"
class Class : public Observer
{
int n1, n2;
public:
Class(Subject* sub);
void setNumbers(int, int);
int sum();
void update();
};
Class.cpp
#include "Class.h"
#include <iostream>
Class::Class(Subject* sub) :Observer(sub) {}
void Class::setNumbers(int a, int b)
{
n1 = a;
n2 = b;
}
int Class::sum()
{
return n1+n2;
}
void Class::update()
{
std::cout << "Class update" << std::endl;
}
Class1.h
#pragma once
#include "Obs.h"
#include "Class.h"
class Class1: public Observer
{
int result;
Class c1, c2;
public:
Class1(Subject* sub);
void setNumbers(Class, Class);
int multiply();
void update();
};
Class1.cpp
#include "Class1.h"
#include <iostream>
Class1::Class1(Subject* sub): Observer(sub) , c1(sub) , c2(sub){}
void Class1::setNumbers(Class a, Class b)
{
c1 = a;
c2 = b;
}
int Class1::multiply()
{
return c1.sum()* c2.sum();
}
void Class1::update()
{
std::cout << "Class1 update" << std::endl;
}
Test.cpp
#include <iostream>
#include "Class.h"
#include"Class1.h"
#include"Subject.h"
int main()
{
Subject sub;
Class c1(&sub), c2(&sub);
c1.setNumbers(1, 3);
c2.setNumbers(4, 6);
std::cout << "1 + 3 = " << c1.sum() << std::endl
<< "4 + 6 = " << " " << c2.sum();
Class1 cl1(&sub);
cl1.setNumbers(c1,c2);
std::cout << "(1 + 3) x (4 + 6) = " << c1.sum() << std::endl;
sub.notify();
return 0;
}

Fuction-definition not allowed RetailItem

I got some problem when run my coding. I got 2 separate file to create RetailItem class and create main. I create both in project.
Below are main.cpp
//main
#include "retailitem.h"
#include <iostream>
#include <iomanip>
using namespace std;
using std::cout;
void displayItem(RetailItem *, const int);
int main()
{
const int Item = 3;
RetailItem ritem[Item] ={ { "Jacket", 12, 59.95 },
{ "Designer Jeans", 40, 34.95 },
{ "Shirt", 20, 24.95 } };
//cout << fixed << setprecision(2);
void displayItem(RetailItem *ritem, const int Item){
cout <<" DESCRIPTION UNITS ON HAND PRICE";
cout<<"=================================================================\n";
for (int i = 0; i < Item; i++)
{
cout << setw(12) << ritem[i].getDesc();
cout << setw(12) << ritem[i].getUnits();
cout << setw(8) << ritem[i].getPrice();
}
cout << "===================================================================";
}
return 0;
}
and there one more file retailitem.h
//RetailItem class
#include <string>
using namespace std;
class RetailItem
{
private:
string description;
int unitsOnHand;
double price;
public:
RetailItem(string,int,double);
void setDesc(string d);
void setUnits(int u);
void setPrice(double p);
string getDesc();
int getUnits();
double getPrice();
};
RetailItem::RetailItem(string desc, int units, double cost)
{
description = desc;
unitsOnHand = units;
price = cost;
}
void RetailItem::setDesc(string d)
{
description = d;
}
void RetailItem::setUnits(int u)
{
unitsOnHand = u;
}
void RetailItem::setPrice(double p)
{
price = p;
}
string RetailItem::getDesc()
{
return description;
}
int RetailItem::getUnits()
{
return unitsOnHand;
}
double RetailItem::getPrice()
{
return price;
}
when compile and run main,
[Error] a function-definition is not allowed here before '{' token
[Error] expected '}' at end of input
I don't know what to fix, how can I solve it?
The error message undoubtedly contained a line number that told you where the problem was. That's an important part of describing the problem. But here it happens to be obvious: void displayItem(RetailItem *ritem, const int Item){ is the start of a function definition. You can't define a function inside another function. Move this outside of main.

Classes in different headers do not recognize each other?

Even though the visual studio pre-compiler or whatever it's called recognizes Graph as a class from a different header, after building I get the most ridiculous errors acting as if I've never mentioned the other headers before. First I didn't forward declare both classes and the first set of errors below come from this, but then I tried forward declaring and there are similar errors related to the structure of the classes themselves. Using functions from another class produce them which shows me the header files do NOTHING. They don't know about each other's functions and I don't know why.
Vertex.h :
#pragma once
#include "Graph.h"
#include <vector>
class Graph;
class Vertex
{
int unique_id;
int longestChain = 0;
int chainComponent_id;
std::vector<int> edges;
Graph* master;
public:
int get_id()
{
return unique_id;
}
int getChainComponent_id()
{
return chainComponent_id;
}
void setChainComponent_id(int id)
{
chainComponent_id = id;
}
int DFS(int, int);
Vertex(int id, std::vector<int> _edges, Graph* _master)
{
unique_id = id;
edges = _edges;
master = _master;
longestChain = 0;
chainComponent_id = -1;
}
};
Graph.h :
#pragma once
#include "Vertex.h"
#include <vector>
#include <iostream>
class Vertex;
class Graph
{
std::vector<Vertex*> vertex;
int amountOfChainComponents = 0;
public:
Vertex* getVertex(int id)
{
if(id<0 || id>vertex.size())
{
return nullptr; //shouldn't be possible with proper input
}
return vertex[id];
}
int getAmountOfChainComponents()
{
return amountOfChainComponents;
}
int longestChain()
{
int longest = 0;
for(int i = 0; i < vertex.size(); i++)
{
if(vertex[i]->getChainComponent_id() == -1)
{
int tmp = vertex[i]->DFS(0, amountOfChainComponents);
amountOfChainComponents++;
if(tmp > longest)
{
longest = tmp;
}
}
}
if(longest == -1)
{
std::cout << "There is a chain for every positive integer" << std::endl;
return -1;
}
if(longest < 2)
{
std::cout << "There is no chain" << std::endl;
return 0;
}
return longest;
}
Graph(std::vector<std::vector<int>> vertices)
{
amountOfChainComponents = 0;
for(int i = 0; i < vertices.size(); i++)
{
Vertex* tmp = new Vertex(i, vertices[i], this);
vertex.push_back(tmp);
}
}
~Graph()
{
while(!vertex.empty())
{
delete vertex[vertex.size() - 1];
vertex.pop_back();
}
}
};
Line Severity Description File 11 Error syntax error: missing ';'
before
'*' c:\users\bico\source\repos\longestchaingraph\longestchaingraph\vertex.h
34 Error '_master': undeclared
identifier c:\users\bico\source\repos\longestchaingraph\longestchaingraph\vertex.h
11 Error missing type specifier - int assumed. Note: C++ does not
support
default-int c:\users\bico\source\repos\longestchaingraph\longestchaingraph\vertex.h
11 Error unexpected token(s) preceding
';' c:\users\bico\source\repos\longestchaingraph\longestchaingraph\vertex.h
30 Error syntax error: identifier
'Graph' c:\users\bico\source\repos\longestchaingraph\longestchaingraph\vertex.h
34 Error 'master': undeclared
identifier c:\users\bico\source\repos\longestchaingraph\longestchaingraph\vertex.h
Line Severity Description File
8 Error 'Vertex': undeclared
identifier c:\users\bico\source\repos\longestchaingraph\longestchaingraph\graph.h
Errors that come after forward declaration:
Line Severity Description File 28 Error use of undefined type
'Vertex' c:\users\bico\source\repos\longestchaingraph\longestchaingraph\graph.h
28 Error left of '->getChainComponent_id' must point to
class/struct/union/generic
type c:\users\bico\source\repos\longestchaingraph\longestchaingraph\graph.h
30 Error use of undefined type
'Vertex' c:\users\bico\source\repos\longestchaingraph\longestchaingraph\graph.h
30 Error left of '->DFS' must point to class/struct/union/generic
type c:\users\bico\source\repos\longestchaingraph\longestchaingraph\graph.h
57 Error use of undefined type
'Vertex' c:\users\bico\source\repos\longestchaingraph\longestchaingraph\graph.h
This is a circular dependency issue; the two header files are including each other.
For both cases, only forward declaration will be enough; declare a pointer to class doesn't need the class to be complete type.
Vertex.h
#pragma once
#include <vector>
class Graph;
class Vertex
{
int unique_id;
int longestChain = 0;
int chainComponent_id;
std::vector<int> edges;
Graph* master;
};
Graph.h
#pragma once
#include <vector>
#include <iostream>
class Vertex;
class Graph
{
std::vector<Vertex*> vertex;
int amountOfChainComponents = 0;
};
EDIT
Move member functions' implementations to implementation files. e.g.
Vertex.h
#pragma once
#include <vector>
class Graph;
class Vertex
{
int unique_id;
int longestChain = 0;
int chainComponent_id;
std::vector<int> edges;
Graph* master;
public:
int get_id();
...
};
Vertex.cpp
#pragma once
#include "Vertex.h"
#include "Graph.h"
int Vertex::get_id()
{
return unique_id;
}
...
Graph.h
#pragma once
#include <vector>
#include <iostream>
class Vertex;
class Graph
{
std::vector<Vertex*> vertex;
int amountOfChainComponents = 0;
public:
Vertex* getVertex(int id);
...
};
Graph.cpp
#pragma once
#include "Vertex.h"
#include "Graph.h"
Vertex* Graph::getVertex(int id)
{
if(id<0 || id>vertex.size())
{
return nullptr; //shouldn't be possible with proper input
}
return vertex[id];
}
...
EDIT2
As #M.M pointed, forward declaration is enough for class Graph in Vertex.h. So you can just remove #include "Graph.h" in Vertex.h, and reserve #include "Vertex.h" in Graph.h.

Deleting an element from vector of type structure

I am trying this piece of code. What I am trying to do is to delete an element from vector of type structure
#include <iostream>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>
using namespace std;
typedef struct _detail
{
int y;
}detail;
typedef struct _list
{
int x;
detail det;
}list;
std::vector<list> v;
list li[5];
void PushElements()
{
for(int i = 0; i < 5; i++)
{
li[i].x = i+2;
li[i].det.y = i+3;
v.push_back(li[i]);
}
}
void display()
{
for(int i = 0; i < v.size(); i++)
{
cout << v[i].x << " ";
cout << v[i].det.y << " ";
}
cout << endl;
}
void DeleteElement()
{
std::vector<list>::iterator it = std::find_if(v.begin(), v.end(), boost::bind(&list::detail::y, _1) == 3);
v.erase(it);
}
int main()
{
PushElements();
display();
DeleteElement();
cout << "After Deleting...................." << endl;
display();
return 0;
}
While compiling I get following errors:
error C3083: 'detail': the symbol to the left of a '::' must be a type
error C2039: 'y' : is not a member of '_list'
error C2065: 'y' : undeclared identifier
I don't understand what this error is and how to solve it. Can somebody help me to solve this error??
&list::detail::y
detail is the name of a type that isn't nested in list. list has a member of type detail named y.
I think you want to form a pointer to member of member, but as far as I can tell, it's not possible. You're better off using a lambda to do the comparisons. Something like:
std::find_if(..., ..., [something](const list& l) { return l.det.y == something; } );
On another note, identifiers beginning with an underscore are reserved in the global namespace. _list and _detail aren't strictly allowed.

Unable to remove missing ; before variable name error

#ifndef PRODUCTS_H
#define PRODUCTS_H
#include "Products.h"
class Products
{
protected:
static int count;
string name_;
float cost_;
public:
Products() // default ctor
{
name_ = "";
cost_ = 0.0f;
count++;
}
Products(string name , float cost) //parametorized ctor
{
name_ = name;
cost_ = cost;
count++;
}
Products(Products &p )
{
name_ = p -> name_;
cost_ = p -> cost_;
}
~Products()
{}
string getName()
{
return name_;
}
void setName(string name)
{
name_=name;
}
float getCost()
{
return cost_;
}
void setCost(float cost)
{
cost_=cost
}
float CalcTotal(Products *p_products) //Not made yet!
{
float total=0.0f;
for(int i = 0 ; i < count; i++)
{
total += p_products->cost_;
p_products ++;
}
return total;
}
Products read()
{
Products size,*p_products;
cout << "Enter Number of Items To Enter:";
cin >> size;
cout << endl;
p_products = new Products[size];
for(int i = 0 ; i < size; i++)
{
cout << "Enter Name:";
cin >> p_products -> name_;
cout << endl << "Enter Cost";
cin >> p_products -> cost_;
cout << endl;
p_products ++;
}
return p_products;
}
void write(Products *p_products)
{
for(int i = 0 ; i < count ; i++,p_products++)
{
cout<<"Products Name:\t\t"<<p_products->name_<<endl;
cout<<"Products Price:\t\t"<<p_products->cost_<<endl;
}
}
};
#endif
My source code is:
#include <iostream>
#include <string>
#include "Products.h"
using namespace std;
static int Products::count;//declaring static variable
int main()
{
Products *p_products,temp;
*p_products=temp.read();
//temp.write();
system("pause");
delete[] Product;
return 0;
}
But I am getting this error which I can not remove:
error C2146: syntax error : missing
';' before identifier 'name_'
Please help me out!Thanks
You should include the string header file in your first file. It looks like it's complaining that it doesn't know what a string is.
You need to add
#include <string>
and change the type of name_ to
std::string name_;
In Products &p, p is a reference to an object of type Products, it's not a pointer.
You have to use operator ., instead of operator -> in order to access reference fields:
Products(Products &p )
{
name_ = p -> name_;
cost_ = p -> cost_;
}
Try moving this line:
using namespace std;
Above the line where you #include "Products.h". But if you're using string in products.h, you should probably be including etc there instead. Also, I believe "using namespace std" is kinda frowned upon.
in your include file, you must declare the string name_ as std::string name_
You need:
std::string name_;
Also, looks like a missing semicolon here:
void setCost(float cost)
{
cost_=cost
}
You're missing a semicolon in this function:
void setCost(float cost)
{
cost_=cost
}