c++ - 对 C++ 中的继承感到困惑(公共(public)和私有(private))

标签 c++ inheritance encapsulation

#include <iostream>
#include <string>
using namespace std ;
enum COLOR { Green, Blue, White, Black, Brown } ;
class Animal {
public :
    Animal() : _name("unknown") {
        cout << "constructing Animal object "<< _name << endl ;
    }
    Animal(string n,COLOR c) : _name(n),_color(c) {
        cout << "constructing Animal object "<< _name << endl ;
    }

    ~Animal() {
        cout << "destructing Animal object "<< _name << endl ;
    }
    void speak() const {
        cout << "Animal speaks "<< endl ;
    }
    void move() const { }
private :
    string _name;
    COLOR _color ;
};
class Mammal:public Animal{
public:
    Mammal(string n,COLOR c):Animal(n,c){
        cout << "constructing Mammal object "<< _name << endl ;
    }
    ~Mammal() {
        cout << "destructing Animal object "<< _name << endl ;
    }
    void eat() const {
        cout << "Mammal eat " << endl ;
    }
};

我今天刚开始从 Java 过渡到 C++,正在练习一些面向对象的编码以了解差异。

在上面的代码中,我无法从 mammal 类访问 _name。

哺乳动物类不继承私有(private)属性吗?在这种情况下,我是否必须为每个继承重新创建这些属性?

最佳答案

您是正确的,您不能从 Mammal 中访问 Animal 的私有(private)属性。但是,如果您来自 Java,这并不是什么新鲜事 - 它在那里的工作方式相同。

有关示例,请参见此链接:Do subclasses inherit private fields?

关于c++ - 对 C++ 中的继承感到困惑(公共(public)和私有(private)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36807474/

相关文章:

c++ - 有什么方法可以修复 CLion 中使用 SFML 的程序的 "command timed out"GDB 错误?

c++ - 在不破坏兼容性的情况下可以在 .so 库中更改什么

C多级继承递归

c# - 允许访问但阻止外部类实例化嵌套类

javascript - 这个 getter-setter 闭包是否有充分的理由以这种方式在其内部对象中声明它的私有(private)属性?

c++ - 预增量比 C++ 中的后增量快 - 真的吗?如果是,为什么?

c++ - 如何判断哪个文件叫c++程序?

swift - 为什么 Swift 类和结构要这样设置?

java子类问题

c# - 创建泛型类型的实例时无法提供参数