如何解决将基类传递给函数,而不是派生一个
我对继承有问题,这是我的示例代码:
#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";
}
};
是否有可能通过将Square类强制转换为Rectangle类型来调用draw函数?
上面的示例和带有指针的示例会导致stackoverflow,因为Square类的print函数正在无限运行。
感谢您的帮助!
解决方法
我不确定这是否是您的意图,但您可以显式调用
{{1}中Rectangle
的{{1}}的特定版本。
print()
使用Square
函数将始终选择更具体的
// draw( dynamic_cast< const Rectangle & >( *this ) );
Rectangle::print();
std::cout << "Drawing square...\n";
的版本(由于draw()
)。
编辑,现在问题已更改:您必须声明
print()
成员函数virtual
一直到层次结构。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。