C++继承实现中派生类属性为空、输出结果异常问题求助
问题根因
存在两个核心错误:
- 派生类
Rectangle和Triangle中重复定义了和基类Polygon完全同名的私有成员变量_name、_width、_height、_polytype,这会导致派生类的方法访问的是子类自己的这组未初始化的成员,而非基类中已经初始化的成员:字符串默认是空值,浮点型默认是0,所以输出为空、面积为0。 - 基类
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
相关产品推荐
相关产品推荐

