I am getting an error and I don't know how to fix it. I checked everything and maybe I overlooked something, but I am not able to find the problem.
Errors:
1>------ Build started: Project: Aquarium, Configuration: Release x64 ------
1> Fish.cpp
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2065: 'Fish': undeclared identifier
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2059: syntax error: '>'
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2976: 'std::vector': too few template arguments
1> C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\vector(682): note: see declaration of 'std::vector'
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(24): error C2061: syntax error: identifier 'Fish'
1> LooseCalculationClass.cpp
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2065: 'Fish': undeclared identifier
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2059: syntax error: '>'
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(21): error C2976: 'std::vector': too few template arguments
1> C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\vector(682): note: see declaration of 'std::vector'
1>c:\users\lloyd17\dropbox\aquarium project\aquarium\aquarium\EntityControl.h(24): error C2061: syntax error: identifier 'Fish'
1>LooseCalculationClass.cpp(7): warning C4551: function call missing argument list
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Fish.h
#pragma once
#include <iostream>
#include <string>
#include "EntityControl.h"
class Fish
{
private:
//location of the fish
unsigned int _xLocation = 0, _yLocation = 0, _zLocation = 0;
//name of fish
std::string nameOfFish;
unsigned int speed;
public:
//constructor
Fish(std::string name, unsigned int fishSpeed)
{
nameOfFish = name;
speed = fishSpeed;
}
//getters
int getX() const;
int getY() const;
int getZ() const;
std::string getName() const;
void changeX(unsigned int x);
void changeY(unsigned int y);
void changeZ(unsigned int z);
void move();
~Fish();
};
Fish.cpp
#include "Fish.h"
int Fish::getX() const
{
return _xLocation;
}
int Fish::getY() const
{
return _yLocation;
}
int Fish::getZ() const
{
return _zLocation;
}
std::string Fish::getName() const
{
return nameOfFish;
}
void Fish::changeX(unsigned int x)
{
_xLocation = x;
}
void Fish::changeY(unsigned int y)
{
_yLocation = y;
}
void Fish::changeZ(unsigned int z)
{
_zLocation = z;
}
void Fish::move()
{
EntityControl entity;
unsigned int x = rand() % entity.getXContainer();
unsigned int y = rand() % entity.getYContainer();
unsigned int z = rand() % entity.getZContainer();
}
Fish::~Fish()
{
}
Aquarium.cpp(Main)
using namespace std;
#include "EntityControl.h"
#include <Windows.h>
#include <time.h>
#include "LooseCalculationClass.h"
#include <thread>
#include "Fish.h"
int main() {
/*Not using new in object definitions so I don't have to delete them afterwards since pointers don't stay in memory*/
bool running = true;
//defining my objects for functions
EntityControl entity;
LooseCalculationClass calc;
vector<Fish*> fishVector;
Fish a("Lloyd", 200);
fishVector.push_back(&a);
std::thread t1(&EntityControl::movementController, entity, &fishVector);
//std::thread t2(&LooseCalculationClass::userInput, calc);
//t2.detach();
t1.detach();
//main gameloop, prints out the results for every fish, waits a bit and then refreshes the screen
while(running){
for (auto Fish_ptr : fishVector) {
calc.printOutXYZ(*Fish_ptr);
Sleep(500000);
system("pause");
//system("cls");
}
}
return 0;
}
EntityControl.h
#pragma once
#include <iostream>
#include <vector>
#include "Fish.h"
#include <random>
#include <array>
#include <Windows.h>
class EntityControl
{
private:
/*Didn't make a separate object because I only
needed the x,y,z of the fish container although it is against the rules of object oriented programming*/
const unsigned int _xContainer = 20;
const unsigned int _yContainer = 60;
const unsigned int _zContainer = 40;
public:
/*grabs the location of a vector of fish pointers, then takes the
vector and accesses every object threw it's data location with dereferencing.
(Controls the movement of the fish and prevents collision)*/
void movementController(std::vector<Fish*> *fishInputVector);//thread!!
//ACHTUNG! fishInput is the fish to check the surrounding of, changing this might bring up unexpected errors
bool CheckCollision(Fish* fishInput , Fish* fishInput2);
int getXContainer() const;
int getYContainer() const;
int getZContainer() const;
~EntityControl();
};
EntityControl.cpp
#include "EntityControl.h"
/*if the container was much larger,
then multiple threads would be a better solution*/
void EntityControl::movementController(std::vector<Fish*> * fishInputVector)
{
while (true) {
for (auto fish_ptr : *fishInputVector) {
}
}
}
bool EntityControl::CheckCollision(Fish * fishInput, Fish * fishInput2)
{
//collision true/false
bool collision = false;
//collision detectors
bool xCollision = false;
bool yCollision = false;
bool zCollision = false;
//fishInput
unsigned int xOriginal = fishInput->getX();
unsigned int yOriginal = fishInput->getY();
unsigned int zOriginal = fishInput->getZ();
//fishInput2
unsigned int xEntity = fishInput2->getX();
unsigned int yEntity = fishInput2->getY();
unsigned int zEntity = fishInput2->getZ();
//directions, (triggerBox)
if (xOriginal - 1 == xEntity || xOriginal + 1 == xEntity || xOriginal == xEntity) { xCollision = true; }
if (yOriginal - 1 == yEntity || yOriginal + 1 == yEntity || yOriginal == yEntity) { yCollision = true; }
if (zOriginal - 1 == zEntity || zOriginal + 1 == zEntity || zOriginal == zEntity) { zCollision = true; }
//returns true if all 3 directions are true
if (xCollision && yCollision && zCollision) { collision = true; }
return collision;
}
int EntityControl::getYContainer() const
{
return _yContainer;
}
int EntityControl::getXContainer() const
{
return _xContainer;
}
int EntityControl::getZContainer() const
{
return _xContainer;
}
EntityControl::~EntityControl()
{
}
It worked before, don't know exactly what has changed. I think everything is declared like it should but this has been bothering me for a while. Putting the classes in another project and running it from there didn't work either. Neither did changing around some variables / removing methods, but again, I might have missed something.
The problem is that when you include EntityControl.h you have also included Fish.h which refers to Fish defined in Fish.h. However EntityControl.h refers to Fish.h which won't get included because of the pragma once directive. If you remove pragma once then you'd get an infinite loop because of circular dependency.
To solve the problem of circular dependencies use forward declarations.
Remove #include "EntityControl.h" from Fish.h and write class EntityControl; instead.
You may also remove #include "Fish.h"; from EntityControl.h and write class Fish; in its stead.
Related
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;
}
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.
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.
I'm trying to pass an instance of this (the instance in question being the GameEngine class) into my PlayerBrain.run method which takes a GameEngine * const argument corresponding to what this is. I'm curious as to what would cause such an error to be thrown in this case, especially when there are no alternative function definitions for run() or anything like that. PlayerBrain is its own class, not descending from anything. So there's no alternative definitions to run that might cause problems. Here's the relevant code:
All public methods in PlayerBrain.h
#pragma once
#include "GameEngine.h"
#include "Species.h"
#include "Neuron.h"
#include "Genome.h"
#include "GenePool.h"
#include "Gene.h"
#include <sys/stat.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <Windows.h>
using namespace std;
class PlayerBrain {
private:
int popSize;
int stalenessThreshold;
int timeoutConstant;
int currentTimeout;
int maxNodes;
int farthestDistance;
bool buttons[6]; // JASON - shoot, left, right, up, down, jump in that order
GenePool p;
bool fileExists(string filename);
bool fitnessAlreadyMeasured();
void nextGenome();
void evaluateCurrent(Genome * g);
void evaluateNetwork(vector<Neuron*> * network, vector<int> inputs);
void loadPool(string filename);
double sigmoid(double sum);
vector<int> getInputs();
Genome templateGenome();
void pressAKey();
void unPressAKey();
vector<INPUT *> oldbuttons;
public:
PlayerBrain();
void intialize();
void run(GameEngine const *);
void close();
};
The actual implementation in its .cpp
void PlayerBrain::run(GameEngine const * g) {
Genome * current = p.getCurrentGenome();
int xPos = 0;
int bossLives = 0;
double fitness;
double timeoutBonus;
unPressAKey();
if ((p.getCurrentFrame() % 5) == 0)
evaluateCurrent(current);
pressAKey();
xPos = g->getXPosAckVar();
bossLives = g->getBossLivesAckVar();
if (xPos > farthestDistance) { farthestDistance = xPos; currentTimeout = timeoutConstant; }
currentTimeout--;
timeoutBonus = p.getCurrentFrame() / 4;
if ((currentTimeout + timeoutBonus) <= 0) {
fitness = (farthestDistance - (p.getCurrentFrame() / 2)) + 2000 * bossLives;
if (fitness == 0) { fitness = -1; }
current->setFitness(fitness);
if (fitness > p.getMaxFitness()) { p.setMaxFitness(fitness); }
p.setCurrentSpecies(0);
p.setCurrentGenome(0);
while (fitnessAlreadyMeasured()) { nextGenome(); }
}
p.setCurrentFrame(p.getCurrentFrame() + 1);
}
The function call in GameEngine.cpp`
while (true)
{
......//irrelevant stuff
if (tickTimeNow > tickTimeTrigger)
{
if (dTimeTrigger > m_PaintTimeTrigger)
{
....
brain->run(this);
....
}
else Sleep(1);
}
else WaitMessage();
}
}
The error I get is as follows:
Error C2660 'PlayerBrain::run': function does not take 1 arguments
I have a class named Model and in ypur .h file I have this:
private:
vector<int> memory(MEMORY_SIZE);
MEMORY_SIZE is a const in a define header with value 10.
when I try compile I'm gettind this error code
Model.h:33: error: ISO C++ forbids declaration of 'vector' with no type
Model.h:33: error: expected ';' before '<' token
I don't know why this, I'm declaring the type of vector...
The complete header code:
/*
* Model.h
*
* Created on: Sep 13, 2012
* Author: ademar
*/
#ifndef MODEL_H_
#define MODEL_H_
#include "Config.h"
#include "Arduino.h"
#include <vector>
class Model {
public:
Model(int pin, char command[]);
Model(int pin, int initialState, char command[]);
bool isChanged(int currentState);
char* getCommand(void);
int getState();
void setRange(int range);
void usesMemory();
private:
int pin;
int state;
int range;
long time;
char* command;
void updateTime();
bool useMemory;
std::vector<int> memory;
};
#endif /* MODEL_H_ */
And the C++ code:
/*
* Model.cpp
*
* Created on: Sep 13, 2012
* Author: ademar
*/
#include "Model.h"
Model::Model(int pin, char command[]) {
*this = Model(pin,0,command);
}
Model::Model(int pin, int initialState, char command[]) {
this->pin = pin;
this->state = initialState;
this->command = command;
this->range = 1;
this->useMemory = false;
this->updateTime();
}
void Model::usesMemory(){
this->useMemory = true;
}
void Model::setRange(int range){
this->range = range;
}
bool Model::isChanged(int currentState) {
if ((currentState >= (this->state + this->range) || currentState <= (this->state - this->range)) && ((this->time+WAIT_CHANGE)<millis())){
this->state = currentState;
updateTime();
return true;
}
return false;
}
char* Model::getCommand(){
return this->command;
}
int Model::getState(){
return this->state;
}
void Model::updateTime(){
this->time = millis();
}
And the error:
In file included from Honda.h:11,
from Honda.cpp:8:
Model.h:33: error: ISO C++ forbids declaration of 'vector' with no type
Model.h:33: error: invalid use of '::'
Model.h:33: error: expected ';' before '<' token
These are my shots that vector is not included or you are missing namespace std::. The compiler explicitly points out that it does not know what vector is.
What is more, you don't initialize fields like this in C++. You have to do it in the constructor:
#include <vector>
#include <iostream>
#define MEMORY_SIZE 10
class Clazz {
std::vector<int> memory;
public:
Clazz() : memory(MEMORY_SIZE){}
int memory_size() {return memory.size();}
};
int main() {
Clazz c;
std::cout << c.memory_size() << std::endl;
return 0;
}