gpt4 book ai didi

c++ - 理解虚函数

转载 作者:太空狗 更新时间:2023-10-29 20:57:37 26 4
gpt4 key购买 nike

// multiple inheritance
#include <iostream>
using namespace std;

class Polygon {
protected:
int width, height;
public:
Polygon (int a, int b) : width(a), height(b) {}
virtual int area()=0;
virtual void print(){
cout << "area = " << area() << endl;
};
};



class Rectangle: public Polygon{
public:
Rectangle (int a, int b) : Polygon(a,b) {}
int area () { return width*height; }
void print(){
cout << "area = " << area() << endl;
};
};

class Square: public Rectangle{
public:
Square (int a, int b) : Rectangle(a,b) {}
int area () { return width*height/2; }
};

int main () {
Square sq (4,5);
sq.print ();
return 0;
}

在这个函数中,print调用了Square(不是Rectangle)的area()。为什么?由于 Rectangle 中的 area() 不是虚拟的,因此它应该从 Rectangle 中调用 area() 。最后的结果是10,按照我的说法应该是20。

最佳答案

Since area() in Rectangle is not virtual, it should call area() from Rectangle

它实际上是virtual,因为它在基类中被声明为virtual。此属性会自动转移到继承类的成员函数声明。

参见标准,虚函数 [class.virtual](强调我的):

If a virtual member function vf is declared in a class Base and in a class Derived, derived directly or indirectly from Base, a member function vf with the same name, parameter-type-list (8.3.5), cv-qualification, and refqualifier (or absence of same) as Base::vf is declared, then Derived::vf is also virtual (whether or not it is so declared) and it overrides Base::vf.


旁注。从矩形导出正方形可以是problematic因为它违反了 Liskov 替换原则。

关于c++ - 理解虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29979527/

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