這個問題在這里已經有了答案: 呼叫虛擬基類的多載建構式 4 個答案 14 小時前關閉。
#include <iostream>
using namespace std;
class Point
{
int x,y;
public:
Point()
{
x=0;
y=0;
}
Point(int x, int y)
{
this->x=x;
this->y=y;
}
Point(Point &p)
{
x=p.x;
y=p.x;
}
friend class Square;
};
class Square
{
Point _point;
int side;
public:
Square() {cout<<"Square.\n";}
Square(Point &p, int side_val): _point(p), side(side_val)
{
cout<<"Square constructor that should be used.\n";
}
};
class Rectangle: public virtual Square
{
int side2;
public:
Rectangle() {}
Rectangle(Point &p, int side_1, int side_2): Square(p,side_1), side2(side_2) {}
};
class Rhombus: public virtual Square
{
Point opposite_point;
public:
Rhombus() {cout<<"Rhombus. \n";}
Rhombus(Point &p, Point &q, int side_1): Square(p, side_1), opposite_point(q)
{
cout<<"Rhombus constructor that should be used \n";
}
};
class Paralellogram: public Rectangle, public Rhombus
{
public:
Paralellogram(Point &p, Point &q, int side_1, int side_2): Rhombus(p,q,side_1),Rectangle(p,side_1,side_2)
{
cout<<"Parallelogram constructor that should be used\n";
}
};
int main()
{
Point down_left(3,5);
Point up_right(2,6);
int side_1=5;
int side_2=7;
Paralellogram par(down_left,up_right,side_1,side_2);
}
我得到的輸出是:
Square
Rhombus constructor that should be used
Paralellogram constructor that should be used
而我想要做的是實體化一個平行四邊形,它結合了來自菱形和矩形的變數(它應該有一個_point,reverse_point,side,side2),我不希望它們加倍,因此我正在使用虛擬繼承。但是我打算使用的 Square 的建構式永遠不會被呼叫,即使是一次,而是會呼叫基本建構式。
我該怎么辦?放棄虛擬繼承?
uj5u.com熱心網友回復:
在虛繼承中,虛基是根據派生最多的類來構造的。
class Paralellogram: public Rectangle, public Rhombus
{
public:
Paralellogram(Point &p, Point &q, int side_1, int side_2) :
Square(), // You have implicitly that
Rectangle(p,side_1,side_2),
Rhombus(p,q,side_1)
{
cout<<"Parallelogram constructor that should be used\n";
}
};
你可能想要
class Paralellogram: public Rectangle, public Rhombus
{
public:
Paralellogram(Point &p, Point &q, int side_1, int side_2) :
Square(p, side_1),
Rectangle(p,side_1,side_2),
Rhombus(p,q,side_1)
{
cout<<"Parallelogram constructor that should be used\n";
}
};
uj5u.com熱心網友回復:
如了解虛擬基類和建構式呼叫中所述:
始終只有一個建構式呼叫,并且始終是您實體化的實際具體類。您有責任為每個派生類賦予一個建構式,該建構式在必要時呼叫基類的建構式,就像您在 [Rectangle and Rhombus] 的建構式 [s] 中所做的那樣。
問問自己:如果Rectangle和呼叫不同意應該如何初始化Rhombus的唯一(因為虛擬)實體怎么辦?Square我們應該聽誰的?答案都不是。當前類(此處)始終負責Parallelogram初始化虛基。并且由于這里沒有指定建構式,所以認為Parallelogram呼叫了Square.
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456222.html
上一篇:我無法實作自定義包
下一篇:檢查點擊事件是否存在元素
