如何调用基类的运算符==?

时间:2014-10-05 23:34:18

标签: c++

我的问题是我不知道要写哪些内容我写了 HELP_HERE (请参阅上面的代码类函数bool operator ==中的代码)以获得他两只狗的动物类型之间的比较。每只狗都是动物,所以我需要能够返回代表“狗内动物”的变量。在java中,我可以使用super(),它在c ++中需要什么?

`

#include "Animal.h"


class Dog : public Animal
   {
      private:
      char _name;
      int _age;
      int _hps;
      float _peso; // peso is Weight
public:
Dog(char name,int age, float peso, int hps) : Animal(name,age),_peso(peso),_hps(hps) {}

void roar(std::ostream &os) const {
    os << "O cao " << _name << " esta a ladrar\n.";
}
 int Vidas() const {
    return _hps;
}
float Peso() const {
    return _peso;
}
int returnAnimal() {
    return animal.Age();
}
bool operator==(const Dog &dog) {

    return HELP_HERE.operator==(dog.HELP_HERE) &&
        dog.Vidas() == _hps && dog.Peso() == _peso; 
}

friend std::ostream &operator<<(std::ostream &os, const Dog &dog) {
    dog.roar(os);
    return os;
}
};`

动物类:

#ifndef ANIMAL_H
#define ANIMAL_H
#include <iostream>


class Animal {
   int _age;
   char _name;
public:
   Animal(int age) : _age(age),_name('-') {}
   Animal(int age, char name) : _age(age), _name(name) {}

   int Age() const { return _age; }
   char Name() const { return _name; }

   friend std::ostream &operator<<(std::ostream &os, const Animal &animal) {
       animal.sleep(os);
       return os;
   }
   void sleep(std::ostream &os) const {
      os << "the animal " << Name() << " is sleeping.\n";
   }
   void Age(int age) { _age = age; }
   bool operator==(const Animal &animal) { 
      return _age == animal.Age() && _name == animal.Name(); 
   }
};

#endif // ANIMAL_H

1 个答案:

答案 0 :(得分:0)

HELP_HERE.operator==(dog.HELP_HERE)更改为:

Animal::operator==(dog)

通常,您可以使用Animal &a = *this;获取Animal参考。 C ++没有一个表示&#34;父类&#34;的关键字,但是你总是可以让你的子类包含typedef Animal super;,然后你可以使用super::operator==或{{ 1}}等等。

相关问题