C ++链接2个类一起怎么样 [英] C++ linking 2 classes together how

查看:144
本文介绍了C ++链接2个类一起怎么样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能有些微不足道,但我对这种问题感到困惑。



我想创建两个类Class1,Class2。这两个类应该包含一个包含指向其他类的实例的指针的字段。所以他们应该是交叉链接。



如果我这样做,那么我从编译器得到一个错误:
- ISO C ++禁止声明Class1 '没有类型
- 预期';'前* token



请帮助:)

file:class1.h

  #ifndef CLASS1_H 
#define CLASS1_H

#include class2.h

class Class1 {
public:
Class1();
private:
Class2 * link;
}

#endif

file:class2.h

  #ifndef CLASS2_H 
#define CLASS2_H

#includeclass1.h

class Class2 {
public:
Class2();
private:
Class1 * link;
}

#endif


解决方案>

在使用它之前添加类声明(而不是定义)。例如,您可以:

  #ifndef CLASS1_H 
#define CLASS1_H

Class2;

class Class1
{
public:
Class1();
private:
Class2 * link;
}

#endif

.h。


this maybe a little trivial but I'm puzzled with such problem.

I want to create two classes Class1, Class2. Both classes should contain a field that contains pointer to instance of the other class. So they should be cross linked.

If I do it like this then I get an error from the compiller saying: - ISO C++ forbids declaration of 'Class1' with no type - expected ';' before * token

Please help :)

file: class1.h

#ifndef CLASS1_H
#define CLASS1_H

#include "class2.h"

class Class1 {
public:
    Class1();
private:
    Class2* link;
}

#endif

file: class2.h

#ifndef CLASS2_H
#define CLASS2_H

#include "class1.h"

class Class2 {
public:
    Class2();
private:
    Class1* link;
}

#endif

解决方案

Add class declaration (as opposed to definition) before you use it. For example, you could have:

#ifndef CLASS1_H
#define CLASS1_H

class Class2;

class Class1
{
public:
    Class1();
private:
    Class2* link;
}

#endif

and do the same for Class2.h.

这篇关于C ++链接2个类一起怎么样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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