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

C++继承实现中派生类属性为空、输出结果异常问题求助

问题根因

存在两个核心错误:

  1. 派生类Rectangle和Triangle中重复定义了和基类Polygon完全同名的私有成员变量_name、_width、_height、_polytype,这会导致派生类的方法访问的是子类自己的这组未初始化的成员,而非基类中已经初始化的成员:字符串默认是空值,浮点型默认是0,所以输出为空、面积为0。
  2. 基类Polygon的成员变量权限是private,即便删掉派生类的重复成员,子类也无法直接访问基类的私有成员,会触发编译错误。
修复步骤
  • 第一步:将基类Polygon的成员变量权限从private修改为protected,允许派生类直接访问继承得到的成员。
  • 第二步:删掉Rectangle和Triangle中重复定义的所有私有成员变量,直接使用继承自基类的成员即可。
  • 可选优化:派生类中如果方法逻辑和基类完全一致(比如Rectangle的calcArea、两个派生类的getName),可以不用重写,直接复用基类的实现即可,简化代码。
修正后的核心代码示例
// 基类修改权限部分
class Polygon
{
public:
    Polygon(string name, double width, double height){
        _name = name;
        _width = width;
        _height = height;
        _polytype = POLY_PLAIN;
    }

    virtual ~Polygon()
    {
        cout << "Destroying polygon" << endl;
    }

    virtual Polytype getPolytype(){
        return _polytype;
    }

    virtual void setPolytype(Polytype polytype){
        _polytype = polytype;
    }

    virtual string getName(){
        return _name;
    }

    virtual double calcArea(){
        return _width * _height;
    }

// 这里把private改成protected
protected:
    string _name;
    double _width;
    double _height;
    Polytype _polytype;
};

// Rectangle类删除重复私有成员后的示例
class Rectangle: public Polygon
{
public:
    Rectangle(string name, double width, double height) : Polygon(name, width, height){
        _polytype = POLY_RECT;
    };

    ~Rectangle()
    {
        cout << "Destroying rectangle" << endl;
    }
};

// Triangle类删除重复私有成员后的示例
class Triangle: public Polygon
{
public:
    Triangle(string name, double width, double height) : Polygon(name, width, height){
        _polytype = POLY_TRIANG;
    };

    ~Triangle()
    {
        cout << "Destroying triangle" << endl;
    }

    // 三角形面积计算逻辑不同,保留重写
    double calcArea() override {
        return 0.5 * _width * _height;
    }
};
修复后运行输出
Name is RectA
Name is TriangB
RectA's area is 200.000000
TriangB's area is 100.000000
Destroying triangle
Destroying polygon
Destroying rectangle
Destroying polygon

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:36:06