Hey guys, I'm having an issue with what I think is circular dependency, or just poor code layout.
I take 2 headers. Player.h and Group.h and have the two to include each other. With or without header guards (#ifdef, or #pragma once) does not fix the issue.
I come from a background of C#, where doing things like this is super easy. There are no includes, everything is exposed via namespaces.
Can anyone knowledgeable on C++ clarify on some of these things?
If I forward declare a class, I can't call the members or variables of said class. I can however, use it as name to point to a reference of it. Is there no other alternative?
Basically, I want a Player class, and a Group class. The Group class holds an array of Player. While each player has a Group instance tracking each Player in the group.
After working for 3 days on this, I figured out today, something I
can do is take both header files, forward declare the appropriate class, and use it in the .cpp file, but it seems very wrong.
Blu.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#ifndef BLU_H
#define BLU_H
#include "stdafx.h"
//#include "Red.h" .. Can't put this here.
class Red;
class Blu {
public:
std::string Name;
Red *red;
Blu();
void PrintEnemyName();
void PrintMyName();
};
#endif
|
Blu.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include "stdafx.h"
#include "Blu.h"
#include "Red.h"
Blu::Blu() {
*red = Red();
}
void Blu::PrintEnemyName() {
std::cout << "Blu's Enemy Name: " << Blu::red->Name << "\n";
}
void Blu::PrintMyName() {
std::cout << "Blu's Name: " << Blu::Name << "\n";
}
|
Red.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#ifndef RED_H
#define RED_H
#include "stdafx.h"
//#include "Blu.h"
class Blu;
class Red {
public:
std::string Name;
Blu *blu;
Red();
void PrintEnemyName();
void PrintMyName();
};
#endif
|
Red.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include "stdafx.h"
#include "Red.h"
#include "Blu.h"
Red::Red() {
*blu = Blu();
}
void Red::PrintEnemyName() {
std::cout << "Red's Enemy Name: " << Red::blu->Name << "\n";
}
void Red::PrintMyName() {
std::cout << "Red's Name: " << Red::Name << "\n";
}
|
main.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include "stdafx.h"
#include "Red.h"
#include "Blu.h"
int _tmain(int argc, _TCHAR* argv[])
{
Red red = Red(); // Create an instance of each class.
Blu blu = Blu();
red.Name = "RED Object.";
red.blu = &blu; // Create instance of "blu" within red.
red.blu->Name = "RED Object's enemy. BLU.";
red.blu->PrintMyName(); // Seems methods are exposed with this class acting as a third party. I believe it is because this class does not declare Red or Blu, so it can include both Red and Blu.
system("pause");
return 0;
}
|
If anyone can clarify or maybe lead me on the right path, I'd be very appreciative. Thanks,
Mark.