对父级的类引用

时间:2010-03-06 14:28:43

标签: c++ oop class parent-child

我很擅长使用C ++而且我实际上遇到了问题。

我有一些A,B,C类定义如下(PSEUDOCODE)

class A
{
...
    DoSomething(B par1);
    DoSomething(C par1);
...
}

class B
{
   A parent;
...
}

class C
{
   A parent;
...
}

问题是:

如何制作?如果我只是这样做(因为我总是在c#中完成)它会给出错误。我非常理解这个的原因。 (如果我将B和C的引用(include)添加到自己的头文件中,则尚未声明A)

有什么方法可以解决这个问题吗? (使用void *指针不是imho的方法)

4 个答案:

答案 0 :(得分:5)

Forward-declare BC。这样编译器就会在到达类A的定义之前知道它们存在。

class B;
class C;

// At this point, B and C are incomplete types:
// they exist, but their layout is not known.
// You can declare them as function parameters, return type
// and declare them as pointer and reference variables, but not normal variables.
class A
{
    ....
}

// Followed by the *definition* of B and C.

P上。 S上。

另外,还有一个与问题无关的提示(看看你是如何来自C#背景的):it's better to pass by const reference than by value

class A
{
...
    void DoSomething(const B& par1);
    void DoSomething(const C& par1);
...
}

答案 1 :(得分:3)

对于函数声明,如果未在那里定义函数,则允许参数类型不完整:

class B;
class C;

class A
{
...
    R DoSomething(B par1);
    R DoSomething(C par1);
...
}

class B
{
   A parent;
...
}

class C
{
   A parent;
...
}

inline R A::DoSomething(B par1) { ... }
inline R A::DoSomething(C par1) { ... }

因此,您只需在BC完成后定义它们。但由于它们是在类外部定义的,因此将它们设为inline,因此不同转换单元中的多个定义不会导致链接器错误。

答案 2 :(得分:2)

你应该在A:

之前转发声明B和C类
class B;
class C;

class A {
    ...
};

在A中引用B和C的点,编译器只需要知道它们是什么类型的动物。使用前向声明,您满足编译器。然后你可以正确定义它们。

答案 3 :(得分:1)

使用前瞻声明

您可以定义A类;没有它的实现,在B和C之前,然后再定义它

相关问题