C ++纯虚拟虚空

时间:2014-02-12 20:34:27

标签: c++ class inheritance polymorphism syntax-error

我一直在阅读有关多态的内容并决定创建一个程序。在基类中,我使它变得抽象,因此派生类可以无错误地使用它。但是当我试图给派生类一个对象时,它说

  

2 IntelliSense:不允许抽象类类型为“Son”的对象:             行: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;
}

谢谢

2 个答案:

答案 0 :(得分:5)

你有一个问题。请参阅以下声明:

virtual void getProf_getName() = 0;

您使用签名

重新实现了getProf_getName()
void getProf_getName(string hName, string hProf);
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^
//                      different parameters

这些功能不同,你没有重新实现虚拟,所以编译器自然会抱怨他没有找到你在基类中声明的纯虚拟的任何实现。

至于错误消息:因为你没有重新实现所有虚函数,Son本身就是一个抽象类。

答案 1 :(得分:0)

您的签名不同

    virtual void getProf_getName(string hName, string hProf) = 0; //pure virtual function
相关问题