具有引用彼此的成员的C ++类 [英] C++ classes with members referencing each other

查看:121
本文介绍了具有引用彼此的成员的C ++类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用引用彼此的成员写2个类。我不知道如果我做错了,或者这是不可能的。任何人都可以在这里帮助我...

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
$ b

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:
};

我遇到的错误是:

错误C2143:语法错误:缺少';'before'<'

错误C2238:';'之前的意外标记

错误C4430:缺少类型说明符 - int。

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!

推荐答案

第一个错误 - 您需要明确使用命名空间:

first error - you need to explicitly use the namespace:

std::vector<Router> Routers;

不要使用namespace std;在头文件中

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

其他错误从第一个开始重新生成:)

Other errors are restulting from the first :)

以后,你需要做向前宣布的Router类,put

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

class Router;

加入您的Network.h

into your Network.h

这篇关于具有引用彼此的成员的C ++类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆