c++ - 多态——基类私有(private)成员的子类共享

标签 c++ polymorphism

为什么子类不使用多态性在父类(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

这是错误的。 ab不同的对象。它们每个都有一个 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/

相关文章:

python - 如何通过 ZeroMQ 将图像(opencv 矩阵/numpy 数组)从 C++ 发布者传输到 python 发送者?

c++ - Google 如何处理 C++ 中的错误

c++ - "Deep"使用模板元编程在 C++ 中进行函数柯里化(Currying)

python - 多态性和来自模块的调用

haskell - Haskell 中的变量关联类型/数据类型

c++ - 清除 vector<pointer> 然后重新使用它

c++ - 尝试调试 TensorFlow C++ 代码时 GDB 退出/崩溃

c++ - 是否可以根据约束 "overload"别名模板?

polymorphism - decltype 和 typeid 返回不同的类型

c++ - 执行一个函数来影响不同的模板类实例