通过派生类C ++访问派生类的基类

时间:2018-02-01 16:50:55

标签: c++ inheritance

函数whoAmI()应该返回:

I am a Man
I am a Omnivore

但它只返回"I am a Man"两次:

class Animal
{
public:
  string className;
};

class Omnivore:public Animal
{
 public:
    Omnivore()
    {
        className = "Omnivore";
    }
};

class Man:public Omnivore
{
public:
    Man() {
        className = "Man";
    }
     void whoAmI()
     {
         cout << "I am a " << Omnivore::className << endl;
         cout << "I am a " << Omnivore::Animal::className << endl;
     }
};

2 个答案:

答案 0 :(得分:1)

只有一个Animal::className,由std::string的构造函数初始化为空Animal,然后由"Omnivore"的构造函数分配给Omnivore,然后由Man的构造函数分配给Man。所以你得到了相同的结果,因为它们引用了相同的数据成员。

您可以让他们拥有自己的同名数据成员;但请注意,这不是一个好主意,派生类中的名称将隐藏基类中的名称。 e.g。

class Animal
{
public:
  string className;
};

class Omnivore:public Animal
{
 public:
    string className;
    Omnivore()
    {
        className = "Omnivore";
    }
};

class Man:public Omnivore
{
public:
    string className;
    Man() {
        className = "Man";
    }
     void whoAmI()
     {
         cout << "I am a " << Omnivore::className << endl;         // "Omnivore"
         cout << "I am a " << Omnivore::Animal::className << endl; // empty
         cout << "I am a " << className << endl;                   // "Man"
     }
};

答案 1 :(得分:1)

通常以这种方式完成:

class Animal
{
public:
  static string className() { return "Man"; };
};

class Omnivore:public Animal
{
public:
  static string className() { return "Omnivore"; };
  void whoAmI()
  {
      cout << "I am a " << Omnivore::className() << endl;
      cout << "I am a " << Animal::className() << endl;
  }
};