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

C++重写类成员报错:未覆盖基类成员及double字符串拼接问题

编译错误分析与代码修正

1. 方法重写的核心问题

  • 基类Shape的toString()未加const修饰,子类Rectangle的toString()却带const,导致函数签名不匹配,编译器判定这不是重写而是新函数,因此override关键字触发报错。
  • 基类toString()未声明为virtual,既无法实现多态,也不满足override对基类虚函数的要求。

2. 成员声明错误

基类中double getArea = 0;是非法写法:非静态成员变量不能直接在类内赋值,且题目设计中Shape应为抽象基类,getArea需定义为纯虚函数。

3. 字符串拼接错误

width、height是double类型,不能直接与string拼接,需用std::to_string()转换为字符串后再操作。


修正后的完整代码

#include <iostream>
#include <string>

using namespace std;

class Shape
{
protected:
    string color;
    bool filled;
public:
    Shape() : color("white"), filled(false) {}

    Shape(string c, bool f) : color(c), filled(f) {}

    // 声明为虚函数并添加const,与子类签名匹配
    virtual string toString() const {
        return "Shape[color=" + color + ", filled=" + (filled ? "true" : "false") + "]";
    }

    // 定义为纯虚函数,使Shape成为抽象基类
    virtual double getArea() const = 0;
};

class Rectangle : public Shape
{
protected:
    double width;
    double height;
public:
    Rectangle() : Shape(), width(1.0), height(1.0) {}

    Rectangle(string c, bool f, double w, double h) : Shape(c, f), width(w), height(h) {}

    // 重写基类虚函数,签名完全匹配,override生效
    string toString() const override {
        return "Rectangle[width=" + to_string(width) + ", height=" + to_string(height) + ", " + Shape::toString() + "]";
    }

    // 实现纯虚函数getArea
    double getArea() const override {
        return width * height;
    }
};

// 测试示例
int main() {
    Rectangle rect("red", true, 3.0, 4.0);
    cout << rect.toString() << endl;
    cout << "Area: " << rect.getArea() << endl;
    return 0;
}

修正说明

  • 基类toString()添加virtual和const,确保子类可正确重写。
  • 将getArea改为纯虚函数,符合抽象基类的设计逻辑。
  • 用std::to_string()解决double与string的拼接问题。
  • 子类toString()调用基类方法,满足题目要求的输出格式。
  • 使用初始化列表初始化成员变量,符合C++编码规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 13:22:40