C++纯虚拟虚空

Jim*_*Jim 1 c++ polymorphism inheritance class syntax-error

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

2 IntelliSense:不允许抽象类类型为"Son"的对象:line: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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢

JBL*_*JBL 5

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

virtual void getProf_getName() = 0;
Run Code Online (Sandbox Code Playgroud)

您重新实现getProf_getName()了签名

void getProf_getName(string hName, string hProf);
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^
//                      different parameters
Run Code Online (Sandbox Code Playgroud)

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

至于错误信息:因为你没有重新实现所有的虚函数,Son那么它就是一个抽象类本身.

  • 正如旁注,如果你有一个c ++ 11编译器,那么添加`override`说明符是一个好主意,以防止这些问题滑落(即当基类不是抽象的时). (2认同)