You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 protected access modifier for Human's members means they're accessible to derived classes like Student but not to external code, which is a common middle ground between private and public.
  • Public inheritance (public Human) ensures that public members of Human stay public in Student, which matches Python's default inheritance behavior.
  • We use std::string for string types, which requires including the <string> header.

内容的提问来源于stack exchange,提问作者Miguel Yurivilca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:36:41