gpt4 book ai didi

c++ - 虚继承中的重载虚函数

转载 作者:太空狗 更新时间:2023-10-29 20:58:13 27 4
gpt4 key购买 nike

我的问题有点长。请在完成整个问题后才回答。

我按如下方式实现了菱形继承(钻石问题):

class Polygon
{

protected:
int sides;

public:

Polygon()
{
cout << "Polygon's Default Constructor being called." << endl;
}

Polygon(int a)
{
cout << "Polygon's parameterized Constructor being called." << endl;
sides = a;
}

void virtual Draw()
{
cout << "Polygon being drawn." << endl;
}

virtual ~Polygon()
{
cout << "Polygon's Destructor being called." << endl;
}

};


class Triangle : virtual public Polygon
{
int Angles[3];
public:
Triangle()
{
cout << "Triangle's Default Constructor being called." << endl;

}

Triangle(int a)
{
cout << "Triangle's parameterized Constructor being called." << endl;
sides = a;
}

Triangle(int a, int b) : Polygon(a)
{
cout << "Triangle's double parameterized Constructor being called." << endl;
//sides = a;
}


void virtual Draw()
{
cout << "Triangle being drawn." << endl;
}

~Triangle()
{
cout << "Triangle's Destructor being called." << endl;
}

};

class IsoscelesPolygon : virtual public Polygon
{
void virtual Draw()
{
cout << "Isosceles Polygon's Draw Called." << endl;
}
};

class IsoscelesTriangle : public Triangle, public IsoscelesPolygon
{

void Draw(int )
{
cout << "Isoceles Triangle's Draw() Called." << endl;
}
};

它工作得很好并且解决了由于虚拟继承导致的菱形继承(钻石问题)。但是当我将 IsocelesTriangle 中的 Draw() 更改为 Draw(int) 时,它开始给我这样的错误:

Overloaded Function (virtual in parent class) in Virtual Inheritance

当我将 Polygon 中的 Draw() 设为非虚拟时,此错误不会弹出并且程序成功运行(显然以非多态方式)。为什么?它(基类中的 virtual 函数)与 IsocelesTriangle 中的 Draw() 的签名有什么关系?

最佳答案

我相信这个想法是,如果你不覆盖 IsoscelesTriangle 中的 Draw(并且更改签名不再是覆盖),你最终会得到 2 Draw 函数在最终类 IsoscelesTriangle 中,一个来自 IsoscelesPolygon,另一个来自 Triangle,两者都试图覆盖 Polygon 绘制。编译器发现它有歧义。请注意,g++ 吐出一个更具可读性的错误:

error: virtual function 'Polygon::Draw' has more than one final overrider in 'IsoscelesTriangle'

虚拟继承只是确保基础对象 Polygon 不会在 IsoscelesTriangle 中出现两次。在您的情况下,无论何时您显式覆盖 Draw,编译器都会隐藏来自 TriangleIsoscelesPolygon 的其他 2 个 Draw >,所以不要再混淆了。

PS:即使您从IsoscelesTriangle 中完全删除Draw,您也会发现同样的错误。无论如何,这是个好问题,希望我答对了。


现在,关于你问题的最后一部分

This error doesn't pop up and program successfully runs (in non-polymorphic way obviously) when I make the Draw() in Polygon as non-virtual

这里的想法是,现在每个 TriangleIoscelesPolygon 都将 Draw 声明为 virtual,所以基本上它们开始具有干净的状态,并从 Polygon 重载函数 Draw(它被标记为非虚拟)。然后,您在 IsoscelesTriangle 中得到了 2 个不同的 Draw 函数,它们不会试图覆盖 多边形绘制

关于c++ - 虚继承中的重载虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28122037/

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