0

如何使用多文件程序从派生类中的基类调用构造函数。

IE:我如何将其拆分为一个有四个文件的结构。Person.h、Person.cpp、Student.h 和 Student.cpp。

class Person
{
protected:
    string name;
public:
    Person() { setName(""); }
    Person(string pName) { setName(pName); }
    void setName(string pName) { name = pName; }
    string getName() { return name; }
};
class Student:public Person
{
private:
    Discipline major;
    Person *advisor;
public:
    Student(string sname, Discipline d, Person *adv)
    : Person(sname)
    {
        major = d;
        advisor = adv;
    }
    void setMajor(Discipline d) { major = d; }
    Discipline getMajor() { return major; }
    void setAdvisor(Person *p) { advisor = p; }
    Person *getAdvisor() { return advisor; }
};

我希望它看起来像这样:Person.h

class Person
{
protected:
    string name;
public:
    Person(); 
    Person(string);
    void setName(string)
    string getName()
};

个人.cpp

#include "Person.h"
Person::Person() { setName(""); }
Person::Person(string pName) { setName(pName); }
void Person::setName(string pName) { name = pName; }
string Person::getName() { return name; }

学生.h

class Student:public Person
{
private:
    Discipline major;
    Person *advisor;
public:
    Student(string, Discipline, Person)//call Base class constructor here or .cpp?

    void setMajor(Discipline d) ;
    Discipline getMajor() ;
    void setAdvisor(Person *p) ;
    Person *getAdvisor() ;
};

学生.cpp

#include "Student.h"
#include "Person.h"
Student::Student(string sname, Discipline d, Person *adv)//Call Base class construcotr
{
    major = d;
    advisor = adv;
}
void Student::setMajor(Discipline d) { major = d; }
Discipline Student::getMajor() { return major; }
void Student::setAdvisor(Person *p) { advisor = p; }
Person* Student::getAdvisor() { return advisor; }
};
4

1 回答 1

1

constructor定义时在 Student.cpp 中调用您的基础Student::Student()

Student::Student(string sname, Discipline d, Person *adv)//Call Base class construcotr
: Person(sname)  // <<<<< here
{
    major = d;
    advisor = adv;
}
于 2012-11-27T23:40:16.840 回答