为什么子类不使用多态性在父类(super class)中共享相同的私有(private)成员变量?基类只有一个实例,如果 SubA 通过一个修改器设置私有(private)成员——为什么 SubB 不能访问这个值。如果我希望子类共享同一个私有(private)成员,会是什么样子?
#include <iostream>
class Super {
private:
int cnt;
public:
int getCnt() {
return cnt;
}
void setCnt(int cnt) {
this->cnt = cnt;
}
};
class SubA: public Super {
};
class SubB: public Super {
};
int main() {
Super *super;
SubA a;
SubB b;
super = &a;
super->setCnt(10);
super = &b;
std::cout << super->getCnt() << std::endl;
super = &a;
std::cout << super->getCnt() << std::endl;
return 0;
}
产生:
-8589546555 (garbage)
10
最佳答案
There are only one instance of the baseclass and if SubA
这是错误的。 a
和 b
是不同的对象。它们每个都有一个 A
子对象的实例。您尚未在 b
中设置 cnt
,因此查看它会得到一个垃圾值也就不足为奇了,因为从未初始化的对象读取是未定义的行为.
How would it look like if I want the subclasses to share the same private member?
您可以为基类提供一个static
数据成员。这意味着 A
的所有实例都将共享同一个成员。
关于c++ - 多态——基类私有(private)成员的子类共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30838298/