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

如何创建Satellite父类与Moon子类?代码正确性求证

代码问题解析与修正

你的代码存在几个语法和命名规范问题,我直接给你修正并补充完整的实现逻辑:

1. 核心错误点

  • C++中类定义关键字是小写的class,不是大写的Class
  • 父类名称要与你定义的父类一致:你明确要创建的父类是Satellite,不是复数形式的satellites,类名的大小写和单复数必须严格匹配

2. 完整代码实现

结合题目要求的类结构,完整代码如下:

#include <vector>
#include <string>
#include <iostream>

// 父类:卫星
class Satellite {
protected:
    std::string name;
    double orbit_radius; // 轨道半径(单位:km)
public:
    Satellite(std::string n, double r) : name(n), orbit_radius(r) {}
    // 虚方法,子类可重写实现差异化输出
    virtual void display_info() {
        std::cout << "卫星:" << name << ",轨道半径:" << orbit_radius << "km" << std::endl;
    }
    // 虚析构函数,确保子类对象能被正确销毁
    virtual ~Satellite() = default;
};

// 子类:月球(天然卫星)
class Moon : public Satellite {
public:
    Moon(std::string n, double r) : Satellite(n, r) {}
    void display_info() override {
        std::cout << "天然卫星(月球):" << name << ",轨道半径:" << orbit_radius << "km" << std::endl;
    }
};

// 子类:人造卫星
class ArtificialSatellite : public Satellite {
private:
    std::string mission; // 卫星任务
public:
    ArtificialSatellite(std::string n, double r, std::string m) : Satellite(n, r), mission(m) {}
    void display_info() override {
        std::cout << "人造卫星:" << name << ",轨道半径:" << orbit_radius << "km,任务:" << mission << std::endl;
    }
};

// 行星类,可持有多个卫星
class Planet {
private:
    std::string name;
    std::vector<Satellite*> satellites; // 用父类指针存储,支持多态
public:
    Planet(std::string n) : name(n) {}
    // 添加卫星
    void add_satellite(Satellite* sat) {
        satellites.push_back(sat);
    }
    // 展示所有卫星信息
    void show_all_satellites() {
        std::cout << "行星「" << name << "」的卫星列表:" << std::endl;
        for (auto sat : satellites) {
            sat->display_info();
        }
    }
    // 析构时释放卫星内存
    ~Planet() {
        for (auto sat : satellites) {
            delete sat;
        }
    }
};

// 测试示例
int main() {
    Planet earth("地球");
    earth.add_satellite(new Moon("月球", 384400));
    earth.add_satellite(new ArtificialSatellite("北斗三号", 35786, "全球导航定位"));
    earth.show_all_satellites();
    return 0;
}

3. 关键说明

  • 父类Satellite定义了虚方法和虚析构函数,确保子类可以重写方法实现多态,同时避免内存泄漏
  • 行星类使用std::vector<Satellite*>存储卫星,支持添加任意子类对象,满足“行星可拥有0个或多个卫星”的需求
  • 继承时使用public权限,保证父类的公共成员在子类中保持可访问性,这是最符合业务逻辑的继承方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 08:15:32