如何将Python类继承实现转换为对应的C++类代码?
No worries at all! Converting that Python class inheritance setup to C++ is pretty straightforward once you get the hang of how constructors work with inheritance in C++. Here's the equivalent code, broken down for clarity:
First, we'll need to include the <string> header since we're working with string values. The base Human class will have a constructor that initializes its member variables, and the Student class will inherit from Human—using an initializer list to call the base class constructor (just like super().__init__ in Python).
#include <string> // Base class definition class Human { protected: // Marking these as protected lets derived classes access them if needed std::string firstname; std::string lastname; int age; std::string sex; public: // Constructor for Human Human(const std::string& first, const std::string& last, int age_val, const std::string& sex_val) : firstname(first), lastname(last), age(age_val), sex(sex_val) {} // You can add more member functions here (like getters, setters, or custom methods) }; // Derived class: Student inherits publicly from Human class Student : public Human { private: std::string school; int semester; public: // Student constructor: first calls the Human constructor, then initializes its own members Student(const std::string& first, const std::string& last, int age_val, const std::string& sex_val, const std::string& school_name, int semester_num) : Human(first, last, age_val, sex_val), school(school_name), semester(semester_num) {} // Add any Student-specific functions here };
A few key differences from Python to note:
- Instead of assigning members inside the constructor body, C++ uses an initializer list (the part after the colon) to initialize members directly—this is more efficient and is the standard practice.
- The
protectedaccess modifier forHuman's members means they're accessible to derived classes likeStudentbut not to external code, which is a common middle ground betweenprivateandpublic. - Public inheritance (
public Human) ensures that public members ofHumanstay public inStudent, which matches Python's default inheritance behavior. - We use
std::stringfor string types, which requires including the<string>header.
内容的提问来源于stack exchange,提问作者Miguel Yurivilca
相关产品推荐
相关产品推荐

