更新时间:2023-11-11 19:05:28
不,您不能将 virtual
用于字段,只能用于方法.
No, you cannot use virtual
for fields, only for methods.
但是,您可以通过创建一个返回对字段的引用的函数来模拟:
However you can simulate that by creating a function that returns a reference to a field:
class Base
{
private:
int x;
public:
virtual int& X() { return x; }
};
class Derived : public Base
{
private:
int x;
public:
virtual int& X() override { return x; }
};
int main()
{
Derived d;
Base* b = &d;
b->X() = 100; // will set d's x
}