对父级的类引用

fea*_*l87 3 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;
...
}
Run Code Online (Sandbox Code Playgroud)

问题是 :

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

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

Ale*_*x B 5

前向声明 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.
Run Code Online (Sandbox Code Playgroud)

PS

另外,还有一个与问题无关的提示(看看你是如何来自C#背景的):通过const引用而不是通过值传递更好:

class A
{
...
    void DoSomething(const B& par1);
    void DoSomething(const C& par1);
...
}
Run Code Online (Sandbox Code Playgroud)