【发布时间】:2020-08-13 10:16:52
【问题描述】:
我的继承有问题,这是我的示例代码:
#include <iostream>
struct Drawable {
friend void draw( const Drawable &drawable );
private:
virtual void print() const = 0;
};
void draw( const Drawable &drawable ) {
drawable.print();
}
class Rectangle : public Drawable {
virtual void print() const override {
std::cout << "Drawing rectangle...\n";
}
};
class Square : public Rectangle {
virtual void print() const override {
draw( dynamic_cast< const Rectangle & >( *this ) );
std::cout << "Drawing square...\n";
}
};
int main() {
Square square;
draw( square );
return 0;
}
更具体地说,使用此功能:
struct Square : public Rectangle {
virtual void print() const override {
draw( dynamic_cast< const Rectangle & >( *this ) );
std::cout << "Drawing square...\n";
}
};
有没有可能通过将这个类转换为 Rectangle 类型来调用 Square 类的绘图函数?
上面的例子和带有指针的例子会导致stackoverflow,因为Square类的打印函数无限运行。
感谢您的帮助!
【问题讨论】:
-
是的,可以通过强制转换为 Rectangle 类来调用 Square 类对象的 Square 类的绘制函数。不,您不能在没有终止情况的情况下从 Square 类的绘图函数调用 Square 类的绘图函数,因为这会导致无限递归。
-
您可以复制
Square的Rectangle切片并将其作为临时传递给draw,如下所示:draw(Rectangle(*this)); -
为什么要对派生类隐藏
print()?让它protected。 example
标签: c++ inheritance polymorphism