类似的东西有可能吗?这样会产生错误.
class A {
public:
virtual std::string key;
};
class B : public A {
public:
std::string key;
};
int main()
{
A a;
a.key = "Foo";
return 1;
}
Run Code Online (Sandbox Code Playgroud)
不,因为这没有多大意义.请记住,子类包含其父类的所有成员; 因此,B仍然具有A的std::string key.此外,由于B的std::string key是同一类型的,它是绝对相同于A的-所以是什么重写它的意义呢?
另外,请注意在构造期间,当我们运行A的构造函数时,B不会调用虚方法.这意味着如果我们key在A构造期间访问,我们就会得到A关键 - 但是当B构建时,key它将被遮蔽,其数据完全无法访问.
也就是说,如果你真的想做这样的事情,出于某种原因,你需要使用虚拟访问器功能:
class A {
private:
std::string m_key;
public:
virtual std::string &key() { return m_key; }
virtual const std::string &key() const { return m_key; }
};
class B : public A {
private:
std::string m_key;
public:
virtual std::string &key() { return m_key; }
virtual const std::string &key() const { return m_key; }
};
int main()
{
B b;
b.key() = "Foo";
return 0;
}
Run Code Online (Sandbox Code Playgroud)