C++ 纯虚void

标签 c++ class inheritance polymorphism syntax-error

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

2 IntelliSense: object of abstract class type "Son" is not allowed: 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;
}

谢谢

最佳答案

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

virtual void getProf_getName() = 0;

你用签名重新实现了getProf_getName()

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

这些不是相同的函数,您没有重新实现虚拟,因此编译器自然会提示他没有找到您在基类中声明的纯虚拟的任何实现。

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

关于C++ 纯虚void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21738991/

相关文章:

c++ - 在 C++ 中的堆或堆栈上创建变量

c++ - 与构造函数、类和单独的文件混淆

list - Vaadin:在表中显示列表

c++ - 为什么以及何时使用多态性将基类指向 C++ 中的派生类

c++ - 通过 2d 数组 C++ 传播的最快方法

c# - 在没有任务栏按钮的情况下从 C++ 启动 C# 应用程序

c++ - 我该如何解决此错误 : . exe 文件已停止工作

c++ - 解析 SVG 变换属性的变换列表

php - 我可以从 doctrine2 中的 php 访问鉴别器字段吗?

php - php构造函数中的父/子类型提示?