c++ - 为什么调用基本构造函数而不是带参数的构造函数(虚拟继承)?

标签 c++ oop

#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、opposite_point、side、side2),我不希望它们加倍,因此我正在使用虚拟继承。但是我打算使用的 Square 构造函数永远不会被调用,甚至一次,而是调用基本构造函数。

我该怎么办?放弃虚拟继承?

最佳答案

在虚拟继承中,虚拟基是根据最底层的派生类构造的。

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";
    }
};

关于c++ - 为什么调用基本构造函数而不是带参数的构造函数(虚拟继承)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71754010/

相关文章:

c++ - STL vector 如何提供随机访问

c++ - 当响应跨数据包拆分但 SSL_pending 为零且 SSL_get_error 返回 SSL_ERROR_NONE 时,如何查找是否有更多数据要读取

C++ setenv 解析其他变量

关于 getline(cin, string) 的 C++ 快速问题

matlab - matlab中类库的全局变量

c++ - 为变量和激活记录保留空间

javascript - JS 方法绑定(bind) 2 个不同的 this

c# - 什么时候应该在 C# 中使用 out 和 ref 参数?

php - 在 PHP 中实例化对象后立即使用对象运算符

c++ - 派生类中的虚函数