Python class inheritance to c++

Python class inheritance to c++

本文关键字:c++ to inheritance class Python      更新时间:2023-10-16

在进行C 类之前,我决定首先在Python中进行。

有很好的来源可以参加Python类,但我找不到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 代码中执行相同的操作?

您可以使用初始化器列表在C 中调用超级构造函数并初始化类变量。

作为简化的示例:

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
}

学生构造函数的Human(name, age)部分在基本Human类中调用构造函数。

您评论的Student(string school, int semester)构造函数无法正确初始化Human基类,因为它不包含有关Human(名称,年龄,性别等(的任何信息。