2014-10-05 61 views
0

我的问题是只是我不知道粘贴在哪里我编写了HELP_HERE(请参阅上面的代码Dog中的函数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 
+2

不是'Animal :: operator ==( ...)工作? – 2014-10-05 23:39:15

+0

你在动物和狗身上重复年龄和名字。 – 2014-10-05 23:46:51

+0

我应该在(...)中放置什么? – 2014-10-05 23:47:26

回答

0

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

Animal::operator==(dog) 

一般来说,你可以得到一个动物参考:Animal &a = *this;。 C++没有指示“父类”的关键字,但是您始终可以让您的子类包含typedef Animal super;,然后您可以使用super::operator==super &a = *this;等。

+0

...并且有很多悬挂的额外字符......并且'Animal'中的参数被颠倒过来,比较了从派生类中调用ctor的方式...以及...和...以及... – 2014-10-05 23:56:46

+0

@SaniHuttunen是啊也许我不应该开始与一般的批评:) – 2014-10-05 23:57:04

+0

我是一个noob原谅我xD – 2014-10-05 23:58:56

相关问题