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.
Related
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.
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.
I'm working with c++ STL vectors, and have a vector of structures called projectileList. I'm trying to iterate through the vector, getting and setting values in the struts as I iterate, but my code refuses to compile, with the error 'Incomplete type is not allowed.'
Can anyone please point out what I'm doing wrong:
Code:
ProjectHandeler.h:
#include "stdafx.h"
#include "DataTypes.h"
#include <vector>
class ProjectileHandeler {
private:
int activeObjects;
std::vector<projectile> projectileList;
void projectileUpdater();
public:
ProjectileHandeler(projectile* input[], int projectileCount);
~ProjectileHandeler();
};
#endif
projectileHandeler.cpp
#include "stdafx.h"
#include "DataTypes.h"
#include "ProjectHandeler.h"
#include <vector>
ProjectileHandeler::ProjectileHandeler(projectile* input[], int projectileCount)
{
for (int i = 0; i < projectileCount; i++)
{
projectileList.push_back(*input[i]);
activeObjects += 1;
}
//NO extra slots. Not that expensive.
projectileList.resize(projectileList.size());
}
void ProjectileHandeler::projectileUpdater()
{
while (true)
{
for (unsigned int i = 0; i < projectileList.size(); i++)
{
if (projectileList[i].isEditing == true)
break;
}
}
}
This compiles fine (tested it here: http://codepad.org/cWn6MPJq):
#include <vector>
struct projectile {
bool isEditing;
};
class ProjectileHandeler {
private:
std::vector<projectile> projectileList;
void projectileUpdater()
{
//This bit loops to infinity and beyond! ...or at least untill the handeler is destroyed.
while (true)
{
for (unsigned int i = 0; i < projectileList.size(); i++)
{
if (projectileList[i].isEditing == true) //Throws Incomplete type error
break;
}
}
}
};
int main()
{
}
Notice the removal of *, correct type of loop variable and removal of extra class specifier.
I want to point an array in c++ , is it possible ?
My main code :
#include "ArrayPointerClass.h"
#include "stdafx.h"
#include <iostream>
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
float arr[2];
ArrayPointerClass::pointingArray(&arr);
return 0;
}
ArrayPointerClass.h
#pragma once
static class ArrayPointerClass
{
public:
ArrayPointerClass();
~ArrayPointerClass();
static void pointingArray(float* arr[2]);
};
ArrayPointerClass.cpp
#include "stdafx.h"
#include "ArrayPointerClass.h"
ArrayPointerClass::ArrayPointerClass()
{
}
ArrayPointerClass::~ArrayPointerClass()
{
}
void ArrayPointerClass::pointingArray(float* arr[2]){
float newArray[2] = { 2.2f, 2.2f };
*arr = newArray;
}
I've got this error :
Error 3 error C2653: 'ArrayPointerClass' : is not a class or namespace name c:\users\alex\documents\visual studio 2013\projects\pointerarray\pointerarray\pointerarray.cpp 13 1 PointerArray
Error 3 error C3861: 'pointingArray': identifier not found c:\users\alex\documents\visual studio 2013\projects\pointerarray\pointerarray\pointerarray.cpp 13 1 PointerArray
I know in C++ arrays ,arrays without length defined are not allowed . is it the reason ?
Thanks for your support
There is no way to create a static class in c++. static keyword can be applied to objects and functions.
And each array name is a pointer. Therefore subscripts cannot be given in the parameter. It is sufficient to provide the pointer type.
The modified code which works:
#include <iostream>
#include <string>
using namespace std;
class ArrayPointerClass
{
public:
ArrayPointerClass();
~ArrayPointerClass();
static void pointingArray(float* arr);
};
ArrayPointerClass::ArrayPointerClass()
{
}
ArrayPointerClass::~ArrayPointerClass()
{
}
void ArrayPointerClass::pointingArray(float* arr){
float newArray[2] = { 2.2f, 2.2f };
arr = newArray;
}
int main()
{
float arr[2];
ArrayPointerClass obj;
obj.pointingArray(arr);
return 0;
}
*arr = newArray; will not work you can't copy a C array like that .
You could have done memcpy() or std::copy() like;
memcpy( newArray, arr, 2);
std::copy( newArray, newArray+2, arr);
Thanks everybody for your answers (even there were partially working)
I found my self a solution
// PointerArray.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int* test() {
int size_needed = 2;
int* a = new int[size_needed];
a[0] = 0;
a[1] = 0;
return a;
}
int main()
{
//int arr[2] = { 1, 1 };
int* arr = test();
for (int i = 0; i < 2; i++){
cout << arr[i] << std::endl;
}
cin.get();
return 0;
}
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;
}