Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
530 views
in Technique[技术] by (71.8m points)

pointers - C++ classes with members referencing each other

I'm trying to write 2 classes with members that reference each other. I'm not sure if I'm doing something wrong or it's just not possible. Can anyone help me out here...

Source.cpp

#include "Headers.h"
using namespace std;

void main()
{
    Network* network = new Network();

    system("pause");
    return;
}

Headers.h

#ifndef Headers_h
#define Headers_h

#include <iostream>
#include <vector>
#include "Network.h"
#include "Router.h"

#endif

Network.h

#include "Headers.h"

class Network
{
protected:
    vector<Router> Routers;
};

Router.h

#include "Headers.h"

class Router
{
protected:
    Network* network;
public:
};

The errors I'm getting are:

error C2143: syntax error : missing ';' before '<'
error C2238: unexpected token(s) preceding ';'
error C4430: missing type specifier - int assumed.

I'm pretty sure I'm not missing any semicolons or stuff like that. The program works find if I take out one of the members. I tried finding similar questions and the solution was to use pointers, but that's what I'm doing and it does't seem to be working!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

first error - you need to explicitly use the namespace:

std::vector<Router> Routers;

Don't "use namespace std;" in header files

Other errors are restulting from the first :)

As to the referencing to the class defined later, you need to do forward declaration of Router class, put

class Router;

into your Network.h


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...