虚函数可以设置基类的公共数据成员

Virtual Functions can set publicdata members of base class?

本文关键字:数据成员 基类 设置 函数      更新时间:2023-10-16

setPosition(3,4) 在方法 foo() 中工作,但在派生的虚拟绘制方法中不起作用矩形类。 这不是C++中的功能吗?谢谢。

class Shape
{
public:
       int posX, posY;
public:
    virtual void draw() const = 0;
    void setPosition(int pX, int pY)
    {
        posX = pX;
        posY = pY;
    }
};
class Rectangle : public Shape
{
public:
    virtual void draw() const
    { 
        cout << "Drawing rectangle at " << posX << "  "
           << posY << endl;
            setPosition(3,4);
    }
    void foo()
    {
        setPosition(3,4);
    }
    };

不能从const方法调用非const方法,因为这不会使对象保持不变。

如果draw需要调用setPosition并因此更改Rectangle,则不能将其声明为const

相关文章: