Python class 继承到 c++

Python class inheritance to c++

在做C++之前class,我决定先在Python中做。

Python class 有很好的资源,但我找不到有用的 C++ 资源。

Python代码:

class Human:
    def __init__(self, first, last, age, sex):
        self.firstname = first
        self.lastname = last
        self.age = age
        self.sex = sex
    ...
class Student(Human):
    def __init__(self, first, last, age, sex, school, semester):
        super().__init__(first, last, age, sex)
        self.school = school
        self.semester = semester
    ...

C++ 代码:

class Human {
protected:
    string name;
    string lastname;
    int age;
    string sex;
public:
    Human(string name, string lastname, int age, string sex):
    name(name), lastname(lastname), age(age), sex(sex){
    }
    ~Human();
};
class Student: protected Human{
public:
    string school;
    int semester;
    //Student(string school, int semester);
    ~Student();
};

如何在我的 C++ 代码中做同样的事情?

您可以使用 initializer list.

在 C++ 中调用超级构造函数并初始化 class 变量

举个简单的例子:

class Human {
   int age;
   string name;
 public:
    Human(string name, int age) : age(age), name(name) {} // initializer list
};

class Student : public Human {
    string school;
 public:
    Student(string name, int age, string school)
        : Human(name, age), school(school) {}  // initializer list
}

student构造函数的Human(name, age)部分调用baseHuman中的构造函数class.

您注释掉的 Student(string school, int semester) 构造函数将无法正确初始化 Human 基础 class,因为它不包含有关 Human 的任何信息(姓名、年龄、性别等)。