【问题标题】:Python class inheritance to c++Python 类继承到 C++
【发布时间】:2018-10-05 07:09:29
【问题描述】:

在做 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++ 代码中做同样的事情?

【问题讨论】:

  • 您的问题是什么?请阅读How to Ask
  • 你显然有一些 Python 代码和一些 C++ 代码。 C++ 代码在哪些方面不能满足您的需求?再次,请阅读How to Ask
  • 你想在 c++ 中模拟的 python 代码是什么,这个 c++ 代码如何不满足这些要求?这只是直接继承。为什么需要在 C++ 中对其进行保护? python 类将这些成员公开(我假设是这种情况,因为它们没有前导下划线)。

标签: python c++ class inheritance protected


【解决方案1】:

您可以使用initializer list 在 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 的任何信息(姓名、年龄、性别等)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多