我一直在閱讀有關多態性,並決定創建一個程序。在基類中,我已經將它抽象化了,所以派生類可以無誤地使用它。但是,當我試着給派生類的對象,它說的是C++純虛擬無效
2智能感知:「兒子」是不允許的抽象類類型的對象: 行:38
反正這裏是我的代碼
#include <iostream>
#include <string>
using namespace std;
class Father{
protected:
string prof;
string name;
public:
virtual void getProf_getName() = 0; //pure virtual function
virtual void showProf_showName() = 0; //pure virtual function
};
class Son: public Father{
public:
Son(){} //creating constructor
void getProf_getName(string hName, string hProf){
name = hName;
prof = hProf;
}
void showProf_showName(){
cout << "The son name is " << name << " and he is a " << prof << endl;
}
~Son(){cout << "Deleting Son" << endl;} // deleting memory
};
int main(){
//local variables
string name;
string profession;
//User interface
cout << "What is the name of the son: ";
getline(cin,name);
cout << "What is his profession: ";
getline(cin,profession);
//implementing data
Son son; // Error error C2259: 'Son' : cannot instantiate abstract class line:38 column:1
son.getProf_getName(name,profession);
son.showProf_showName();
//showing info
son.showProf_showName();
system("pause");
return 0;
}
謝謝
'getProf_getName(字符串hName,串HPROF)'是一個不同的功能比'getProf_getName()',所以'Son'類仍然是抽象的,因爲沒有具體落實'getProf_getName()'。 –
作爲一個方面的評論,在使用多態時總是使用虛擬析構函數。 – imreal
作爲另一方的評論,兒子真的是父親嗎? :) – codah