c++ - 在多文件项目中调用基类构造函数

标签 c++ oop

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

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

我希望它看起来像这样: 人.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; }
};

最佳答案

当您定义 Student::Student() 时,在 Student.cpp 中调用您的基础构造函数

Student::Student(string sname, Discipline d, Person *adv)//Call Base class construcotr
: Person(sname)  // <<<<< here
{
    major = d;
    advisor = adv;
}

关于c++ - 在多文件项目中调用基类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13595137/

相关文章:

c++ - Haskell 中的面向对象编程

c++ - 在 C++ 中制作单例 Mixin 类

c++ - 具有一处更改的复制构造函数 : can I get the default copy constructor to do the rest?

c++ - 将字符串和枚举映射到模板化类型

c++ - CMake 中的函数(重新)定义

c++ - 我创建的类似乎错误地设置了它的局部变量

c++ - 在启用 C++ 的 OSX 10.9 上编译 GMP 库

c++ - 在派生类之间复制构造函数

java - 如何将随机生成的数字实现为setter或getter中的变量?

c++ - 基类析构函数如何调用派生析构函数?