C++纯粹的虚空

C++ pure virtual void

本文关键字:纯粹 C++      更新时间:2023-10-16

我一直在阅读有关多态性的文章,并决定创建一个程序。在基类中,我将其抽象化,以便派生类能够毫无错误地使用它。但是当我尝试给派生类一个对象时,它说

2 智能感知:不允许抽象类类型为"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;
}

谢谢

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

virtual void getProf_getName() = 0;

您使用签名重新实现了getProf_getName()

void getProf_getName(string hName, string hProf);
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^
//                      different parameters

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

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

您的签名不同

    virtual void getProf_getName(string hName, string hProf) = 0; //pure virtual function