C++ 继承 - 在子类中运行父方法

标签 c++ inheritance

我的父类 Course 有方法 addStudent(Student s)。我的子类 BetterCourse 继承自 Course。每次我尝试运行 BetterCourse.addStudent(s) 时,我都会收到以下错误:

error: no matching function for call to ‘BetterCourse::addStudent(Student (&)())’ note: candidates are: void Course::addStudent(Student)

我知道它告诉我 addStudent() 尚未在 BetterCourse 中定义,它建议我使用父类 Course 中存在的那个。这让我感到困惑,因为关于继承的整个想法不需要重新定义继承的函数和变量。

类(class)如下:

#include <iostream>
#include <string>
#include "Student.h"

using namespace std;

class Course
{

    protected:
        string id;
        string name;

    public:
        Course();
        Course(string id, string name);     
        void addStudent(Student s);
};

Course::Course()
{
   //code
}

Course::Course(string id, string name)
{
   //code
}

void Course::addStudent(Student s) 
{
   //code
}

更好的类(class):

#include <iostream>
#include <string>
#include "Course.h"

using namespace std;

class BetterCourse : public Course
{
    public:
        BetterCourse(string id, string name) : Course(id,name){};
};

最佳答案

从你的错误来看,你似乎是第一次接触到 C++ 中最丑陋的部分。

这个:

Student s();

是函数声明 - 不是对象定义。 s 类型是 Student (*)() 所以当你调用时:

BetterCourse bc; 
bc.addStudent(s);

您遇到错误 - 您没有方法来添加返回 Student 的函数。

按以下方式定义 Student:

Student s;
Student s {}; // new C++11 way
Student s = Student(); // 

关于C++ 继承 - 在子类中运行父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12877960/

相关文章:

c++ - "using"在这个实例中做什么,存储了什么?

c++ - OpenGL VBO : Drawing a sphere

class - 如何在 Dart 中调用父类(super class)的构造函数和其他语句?

C++ 实现抽象类

c++ - 不同的线程同时访问不同的内存位置

c++ - boost log non-const bitfield 编译错误(向后兼容问题)

c++ - 获取多行输入以在 C++ 中进行解析

c# - 关于C#中构造函数的几个问题

c++ - 这是使用继承的好方法吗?

Swift 4 泛型,引用自身