I have some troubles with my school project.
I have a class:
#include "Group.h"
#include <vector>
#include <string>
using namespace std;
class User{
private :
string username;
vector<Group*> groups;
void show() {
for(int i=0; i<groups.size(); i++)
cout << groups[i]->getName() << "\n";
}
string getUsername(){return username;}
};
and
#include "User.h"
#include <vector>
#include <string>
using namespace std;
class Group{
private :
string name;
string getName(){return name;};
User *f;
vector<User*> m;
void show(){
for(int i=0; i<m.size(); i++)
cout << m[i]->getUsername() << "\n";
}
};
When I try compile it, it gives me errors:
E:\Group.h|31|error: ISO C++ forbids declaration of 'User' with no type| E:\Group.h|31|error: expected ';' before '*' token|
E:\Group.h|33|error: 'User' was not declared in this scope|
E:\Group.h|33|error: template argument 1 is invalid|
E:\Group.h|33|error: template argument 2 is invalid|
E:\Group.h|36|error: 'User' was not declared in this scope|
E:\Group.h|36|error: template argument 1 is invalid|
E:\Group.h|36|error: template argument 2 is invalid|
E:\Group.h|47|error: 'User' has not been declared|
E:\Group.h|47|error: 'User' was not declared in this scope|
E:\Group.h|47|error: template argument 1 is invalid|
E:\Group.h|47|error: template argument 2 is invalid|
E:\Group.h|58|error: ISO C++ forbids declaration of 'User' with no type| E:\Group.h|58|error: expected ';' before '*' token|
E:\Group.h|59|error: 'User' has not been declared|
E:\Group.h|60|error: 'User' was not declared in this scope|
E:\Group.h|60|error: template argument 1 is invalid|
E:\Group.h|60|error: template argument 2 is invalid|
E:\Group.h|61|error: 'User' was not declared in this scope|
E:\Group.h|61|error: template argument 1 is invalid|
E:\Group.h|61|error: template argument 2 is invalid| ||=== Build finished: 21 errors, 4 warnings ===|
what’s wrong?
It compiles only if I add class User; to Group.h file, and class Group; to User.h file but its not the point I’m looking for the right solution, not only the temporary one.
MY WHOLE PROJECT: http://www.speedyshare.com/jXYuM/proj.tar
You have a cyclical dependency. Both files need one another to compile.
Try forward-declaring User in group:
Group.cpp
Then in the Group.cpp file, include User.
You can forward declare in the header anytime the object size doesn’t depend on the actual size of the object your forward declaring. In this case, (in Group) you use User as a pointer and therefore the size of Group is not dependent on the size of User it’s only storing a pointer which is independent of the User size.
Another tidbit which should help is that it’s bad practice to include namespaces (in your case std) in a header file. You should remove the “using” statement and do std::vector instead. Using a “using” in the cpp file is fine, as other code doesn’t “include” your source.