C ++创建双重链接类 [英] C++ creating doubly-linked classes

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

问题描述

我有两个类,它们都需要具有到另一个对象的链接。以下是一些示例代码显示我的问题:

I have two classes which both need to have links to objects of one another. Here's some example code to show my issue:

//object1.h
class object1{
    object2 *pointer;
}

我的其他课程:

//object2.h
class object2{
    object1 *pointer;
}

我不知道我应该如何包括两个类在对方的文件。在两个文件中都有一个包含其他类导致我的问题。最好是,我想在一个文件中只有两个对象,因为它们的头只有几行代码,但是这会导致在文件中首先声明的任何类型的错误,因为其他类的头不是前面它会给我一个无效的类型错误。

I'm not exactly sure how I'm supposed include the two classes simultaneously in each other's file. Having an include for the other class in both files is causing me issues. Preferably, I would like to just have both the objects in one file, since their headers are only a few lines of code each, but this causes an error on whichever class is first declared in the file, since the other class header isn't preceeding it; It gives me an invalid type error.

推荐答案

使用前进声明

//object1.h
class object2;
class object1{
    object2 *pointer;
};

//object2.h
class object1;
class object2{
    object1 *pointer;
};

向前声明引入了不完整类型
简言之,它告诉编译器该定义存在于其他地方。
但是对不完全类型有一些限制。因为编译器不知道它的完整定义,它不能做像为它分配足够的空间,调用成员函数,检查虚表等事情。
从根本上说,你可以做的只是声明引用/指针他们和pass'em周围:

A forward declaration introduces an incomplete type. In short, it tells the compiler that the definition exists somewhere else. You have some limitations with incomplete types, though. Since the compiler doesn't know its full definition, it cannot do things like allocating enough space for it, invoking member functions, checking the virtual table, etc. Fundamentally, what you can do is to just declare references/pointers to them and pass'em around:

// Forward declaration
class X;

class Y {
private:
//  X x;    // Error: compiler can't figure out its size
    X &x;    // A reference is ok
public:
    Y(X &x) : x(x) { }

//  void foo() { x.foo(); } // Error: compiler can't invoke X's member
    void bar();
};

// Full declaration
class X {
public:
    void foo() { }
};

void Y::bar()
{
    x.foo(); // Now it is OK to invoke X's member
}

一个好的模式是使用转发声明以断开头文件或类定义之间的依赖关系循环,让你想知道你的设计可以改进。

A good pattern is to use forward declarations to break dependency cycles between headers or class definitions and make you wonder whatever your design could be improved.

这篇关于C ++创建双重链接类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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