gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:39:59 25 4
gpt4 key购买 nike

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com