本文共 2452 字,大约阅读时间需要 8 分钟。
Diamond problem occurs when we use multiple inheritance in programming languages like C++ or Java.
当我们在诸如C ++或Java的编程语言中使用多重继承时,就会出现钻石问题。
Let’s understand this with one example.
让我们用一个例子来理解这一点。
class A { void display() { //some code }} class B : public A{ void display() { //some code }} class C : public A{ void display() { //some code }} class D : public B, public C{ //contains two display() functions}
Suppose there are four classes A, B, C and D. Class B and C inherit class A. Now class B and C contains one copy of all the functions and data members of class A.
假设有四个类A,B,C和D。类B和C继承了类A。现在,类B和C包含类A的所有函数和数据成员的一个副本。
Class D is derived from Class B and C. Now class D contains two copies of all the functions and data members of class A. One copy comes from class B and another copy comes from class C.
D类是从B和C派生的。现在D类包含A类所有函数和数据成员的两个副本。一个副本来自B类,另一个副本来自C类。
Let’s say class A have a function with name display(). So class D have two display() functions as I have explained above. If we call display() function using class D object then ambiguity occurs because compiler gets confused that whether it should call display() that came from class B or from class C. If you will compile above program then it will show error.
假设类A有一个名为display()的函数。 因此,类D具有两个我上面已经解释过的display()函数。 如果我们使用类D对象调用display()函数,则会产生歧义,因为编译器会混淆应调用来自类B还是来自类C的display()。如果您要编译上述程序,则会显示错误。
This kind of problem is called diamond problem as a diamond structure is formed (see the image).
这种问题被称为钻石问题,因为形成了钻石结构(见图)。
We can remove diamond problem by using virtual keyword. It can be done in following way.
我们可以使用虚拟关键字消除钻石问题。 可以通过以下方式完成。
class A { void display() { //some code }} class B : virtual public A{ void display() { //some code }} class C : virtual public A{ void display() { //some code }} class D : public B, public C{ //contains one display() functions}
You can see we have marked class B and C as virtual. Now compiler takes care that only one copy of data members and functions of class A comes to class D.
您可以看到我们已将B类和C类标记为虚拟。 现在,编译器要注意的是,类D的数据成员和函数只有一个副本。
To remove this problem . Although we can achieve multiple inheritance using interfaces.
为了消除此问题, 。 尽管我们可以使用接口实现多重继承。
Comment below if you found anything missing or incorrect in above diamond problem tutorial.
如果您在上述钻石问题教程中发现任何缺失或不正确的地方,请在下面评论。
翻译自:
转载地址:http://erggb.baihongyu.com/