请阅读代码以了解情况。
#include <iostream>
using namespace std;
class one
{
protected:
int x;
public:
one(int a)
{
x=a;
cout << "one cons called\n";
}
void display(void)
{
cout << "x = " << x << endl;
}
~one()
{
cout << "one destroy\n";
}
};
class two : virtual protected one
{
protected:
int y;
public:
two(int a,int b) : one(a),y(b)
{
cout << "two cons called\n";
}
void display(void)
{
one::display();
cout << "y = " << y << endl;
}
~two()
{
cout << "two destroy\n";
}
};
class three : protected virtual one
{
protected:
int z;
public:
three(int a,int b) : one(a),z(b)
{
cout << "Three cons called\n";
}
void display(void)
{
one::display();
cout << "z = " << z << endl;
}
~three()
{
cout << "three destroy\n";
}
};
class four : private two, private three
{
public:
four(int a,int b,int c) :one(a), two(a,b),three(a,c)
{
cout << " four cons called\n";
}
void display(void)
{
one::display();
cout << "y = " << y << endl;
cout << "z = " << z << endl;
}
~four()
{
cout << "four destroy\n";
}
};
int main()
{
four ob(1,2,3);
ob.display();
return 0;
}
如果我替换代码
four(int a,int b,int c) :one(a), two(a,b),three(a,c)
和
four(int a,int b,int c) :two(a,b),three(a,c)
在我的代码块 ide 中出现类似错误消息:没有匹配的函数用于调用“one::one()”。
如您所见,这是一个基于菱形问题的代码。其中第一个类是grand_parent 类。二、三类为父类,四类为子类。所以我使用了 virtual 关键字来避免歧义。我在这里理解的一切,除非一件事。我知道当父类具有参数化构造函数时,我们需要从派生类向该构造函数提供参数。那么为什么需要为构造函数一提供参数,其中类四只有两个父类,即二和三。
如果我不从类四调用构造函数一,代码会给我编译时错误。请解释为什么我们需要这样做。
最佳答案
该virtual
继承层次结构中的通过确保只有一个one
单一实例存储在one
或two
子歧义消除的基类three
的存在。回想一下,当继承某个类时,派生实例将始终在内部的某个位置存储一个基实例 - 因此 virtual
继承确保 one
内部的 two
和 0x251843122 的实例在继承层次上进一步“下降”
现在的问题是:谁负责初始化这个单个 three
实例?应该是 one
还是 two
?显然不是两者都有,因为只有一个实例。你在这里:它始终是负责初始化 three
的最派生类 - 这是有道理的:嵌入基类拷贝的实例必须对其进行初始化。
这是没有 one
和 four
加上 four
继承的嵌入基类实例的类层次结构的样子:
+----------+ +----------+
| one | | one |
+----+-----+ +----+-----+
| |
| |
+-------+-----------+ virtual +--------+--------+ virtual
| | | |
| | | |
+--------+-------+ +-------+-------+ +----+----+ +----+----+
| two | | three | | two | | three |
| +------------+ | | +----------+ | +----+----+ +----+----+
| | one | | | | one | | | |
| +------------+ | | +----------+ | +--------+--------+
| => must init! | | => must init! | |
+----------------+ +---------------+ +-------+--------+
| four |
| +------------+ |
| | one | |
| +------------+ |
| => must init! |
+----------------+
您可以这样考虑这种机制:
virtual
继承赋予基类实例 virtual
-ness,这包括构造实例 - 这种责任向下传递到层次结构。关于c++ - 在 C++ 中的菱形问题中,为什么我们需要从子类调用祖父构造函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57214656/