2016-01-15 21 views
0

以下代碼給我一個錯誤。重寫'virtual void'C++錯誤

Error: overriding 'virtual void Animal::getClass()', where it says virtual void getClass() { cout << "I'm an animal" << endl; }

Error: conflicting return type specified for 'virtual int Dog::getClass()', where it says getClass(){ cout << "I'm a dog" << endl; }

此外,它說:

Class 'Dog' has virtual method 'getClass' but non-virtual destructor

#include <iostream> 
#include <vector> 
#include <string> 
#include <fstream> 
#include<sstream> 
#include <stdlib.h>  // srand, rand 
#include <stdio.h> 

using namespace std; 

class Animal{ 

public: 
    void getFamily(){ cout << "We are animals " << endl;} 

    virtual void getClass() { cout << "I'm an animal" << endl; } 
}; 

class Dog : public Animal{ 

public: 
    getClass(){ cout << "I'm a dog" << endl; } 

}; 

void whatClassAreYou(Animal *animal){ 

    animal -> getClass(); 

} 

int main(){ 

    Animal *animal = new Animal; 
    Dog *dog = new Dog; 

    animal->getClass(); 
    dog->getClass(); 

    whatClassAreYou(animal); 
    whatClassAreYou(dog); 


    return 0; 
} 
+1

至於虛析看到:當使用虛擬析構函數?(http://stackoverflow.com/a/461237),因爲你的類有一個虛函數它應該也有一個虛擬的析構函數。 –

+1

如果你在多態上下文中破壞你的類,你應該添加一個虛擬析構函數。如果這個定義還沒有響起,那麼只需要添加一個。請注意,在@SalahSalah的例子中根本沒有析構函數調用。 – dascandy

回答

3

更改類犬中的定義:

void getClass() { /* ... */ } 

當你沒有返回類型聲明它,則編譯器將返回類型爲int。這會產生錯誤,因爲overriden方法必須具有與其覆蓋的基類方法相同的返回類型。

+2

默認'int'返回類型甚至不被C++標準支持(它在C中不推薦使用),並且應該在每個現代編譯器中提供有關缺少(返回)類型的警告/錯誤。 –

1

您正在嘗試聲明函數,而不使用舊版C++中允許的返回類型。但ISO C++標準不允許這樣做(儘管有些編譯器可能仍然允許,我想Codegear C++ Builder 2007根本不顯示任何錯誤或警告)。已經在標準中提到了--7/7腳註78和§7.1.5/ 2腳註80:隱式int禁止

這就是爲什麼它被丟棄的原因:

void HypotheticalFunction(const Type); 

在此功能中,這將是自變量型 - 或類型的參數的常量參數const int的與名稱類型?

這裏是一個更好的版本,你可以如何定義你的類:

#include <iostream> 
#include <vector> 
#include <string> 
#include <fstream> 
#include<sstream> 
#include <stdlib.h>  // srand, rand 
#include <stdio.h> 

using namespace std; 

class Animal{ 

public: 
void getFamily(){ cout << "We are animals " << endl;} 

virtual void getClass() { cout << "I'm an animal" << endl; } 
}; 

class Dog : public Animal{ 

public: 
virtual void getClass(){ cout << "I'm a dog" << endl; } 

}; 

void whatClassAreYou(Animal *animal){ 

animal -> getClass(); 

} 

int main(){ 

Animal *animal = new Animal; 
Dog *dog = new Dog; 

animal->getClass(); // I'm an animal 
dog->getClass();  // I'm a dog 

Animal *animal1 = new Dog; 
animal1->getClass(); // I'm a dog 

whatClassAreYou(animal1); // I'm a dog 

whatClassAreYou(animal); // I'm an animal 

return 0; 
} 
0

§ C.1.6 Change: Banning implicit int In C++
a decl-specifier-seq must contain a type-specifier , unless it is followed by a declarator for a constructor, a destructor, or a conversion function.

你缺少你type-specifier這是在現代C++違法。

用途:

void getClass(){ cout << "I'm a dog" << endl; }