首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在C++子类中使用虚拟函数

无法在C++子类中使用虚拟函数
EN

Stack Overflow用户
提问于 2020-05-19 16:35:12
回答 1查看 67关注 0票数 0

我正在制作一个虚拟函数程序,其中有三个班的人,教授和学生。人是由两位学生教授共同继承的。这里我想输入一些教授和学生的参数。为了输入和输出它们,我在每个类中都生成了、getdata、putdata。在person类中,这些函数实际上是定义的。但在代码中我有一些errorsi.ie -

代码语言:javascript
复制
Solution.cpp: In function ‘int main()’:
Solution.cpp:84:26: error: invalid new-expression of abstract class type ‘Professor’
             per[i] = new Professor;
                          ^~~~~~~~~
Solution.cpp:20:7: note:   because the following virtual functions are pure within ‘Professor’:
 class Professor : public Person
       ^~~~~~~~~
Solution.cpp:16:18: note:   ‘virtual void Person::putdata()’
     virtual void putdata() = 0;
                  ^~~~~~~
Solution.cpp:87:27: error: invalid new-expression of abstract class type ‘Student’
         else per[i] = new Student; // Else the current object is of type Student
                           ^~~~~~~
Solution.cpp:42:7: note:   because the following virtual functions are pure within ‘Student’:
 class Student: public Person
       ^~~~~~~
Solution.cpp:16:18: note:   ‘virtual void Person::putdata()’
     virtual void putdata() = 0;
                  ^~~~~~~  
代码语言:javascript
复制
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class Person
{
    public:
    string name;
    int age;

    virtual void getdata() = 0;
    virtual void putdata() = 0;

};

class Professor : public Person
{
    public:
    static int cur_id;
    int publications; 

    Professor() {
        cur_id++;
    }

    void getdata( )
    {

        cin>>name>>age>>publications;
    }

    void pushdata()
    {
        cout<<name<<" "<<age<<" "<<publications<<"\n";
    }
};

class Student: public Person
{
    public:
    static int cur_id;
    int marks[6];

    Student(){cur_id++;}

    void getdata()
    {
        cin>>name>>age;
        int i=0;
        for(i = 0;i<6;i++)
          cin>>marks[i];
    }

    void pushdata()
    {
        cout<<name<<" "<<age;

        int i=0,sum=0;
        for(i = 0;i<6;i++)
          sum += marks[i];

        cout<<" "<<sum<<" "<<cur_id;
    }
};

int Professor::cur_id = 1;
int Student::cur_id = 1;
int main(){
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-19 16:37:44

这一职能:

代码语言:javascript
复制
void pushdata()
    {
        cout<<name<<" "<<age<<" "<<publications<<"\n";
    }

不覆盖Person中的纯虚函数Person

相反,请做:

代码语言:javascript
复制
void putdata() override
    {
        cout<<name<<" "<<age<<" "<<publications<<"\n";
    }

注意,如果将override放在要重写的函数上,则如果您出错,编译器将给出一个错误。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61896203

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档