将基类传递给函数,而不是派生一个

问题描述

我对继承有问题,这是我的示例代码

#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一直到层次结构。