简体   繁体   中英

C++ Inheritance - Running Parent Method in Child Class

My parent class, Course, has the method addStudent(Student s). My child class, BetterCourse, inherits from Course. Every time I try to run BetterCourse.addStudent(s), I get the following error:

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

I understand it's telling me addStudent() hasn't been defined in BetterCourse and that it's recommending I use the one present in the parent class, Course. This has me confused as the whole idea around inheritance is not needing to redefine inherited functions and variables.

Course is as follows:

#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
}

BetterCourse:

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

using namespace std;

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

From your error it seems that you for the first time get to the ugliest part of C++.

This:

Student s();

Is function declaration - not object definition. s type is Student (*)() so when you call:

BetterCourse bc; 
bc.addStudent(s);

You get your error - you don't have method to add functions returning Student.

Define Student in the following ways:

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

It sounds like you're actually calling the function 'addStudent' with an inappropriate argument. Could you show the code that is actually calling addStudent on the BetterCourse object? It sounds like you're using a reference to the student instead of the student object itself.

you can not call BetterCourse.addStudent(s) you should create an object

BetterCourse obj;
obj.addStudent(s);

should work

If you want to call BetterCourse::addStudent(s) than declare addStudent(s) as static method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM