2014-10-05 39 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

相關問題