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

C++派生类调用基类函数设置成员值报错求助

问题分析与解决

你的代码存在两个核心问题:

  1. Vehicle类无参构造仅声明未实现:创建Car对象时,Car的无参构造会默认调用基类Vehicle的无参构造,但编译器找不到该构造函数的定义,会触发链接错误。
  2. 缺少头文件:代码中使用了std::string但未引入对应头文件,会导致编译错误。

解决步骤:

1. 实现Vehicle的无参构造函数

可以在Vehicle类内直接定义,两种方式任选其一:

// 方式一:使用默认构造(C++11及以上版本支持)
Vehicle() = default;

// 方式二:手动初始化成员变量
Vehicle() : garage_spaces_(0), num_wheels_(0) {}

2. 添加头文件

在代码开头加入#include <string>,确保std::string能被编译器识别。

修改后的完整代码

#include <iostream>
#include <string>
using namespace std;

class Vehicle
{
public:
    // 实现无参构造,手动初始化成员
    Vehicle() : garage_spaces_(0), num_wheels_(0) {}
    
    void setGarageSpaces(size_t spaces)
    {
        garage_spaces_ = spaces;
    }
    
    void setNumWheels(size_t wheels)
    {
        num_wheels_ = wheels;
    }

    // 实现有参构造,初始化成员
    Vehicle(std::string name, std::string manufacturer, double top_speed, double weight, double mpg, double curr_gas_amt)
        : garage_spaces_(0), num_wheels_(0) {}

protected:
    size_t garage_spaces_;
    size_t num_wheels_;
};

class Car : public Vehicle {
public:
    Car(){
        setGarageSpaces(2);
        setNumWheels(4);
    }
    
    // 实现Car的有参构造,调用基类有参构造
    Car(std::string name, std::string manufacturer, double top_speed, double weight, double mpg)
        : Vehicle(name, manufacturer, top_speed, weight, mpg, 0.0) {}
};

int main() {
    Car c;
    // 可选:添加测试代码验证设置结果
    // 在Vehicle类中添加getter函数:
    // size_t getGarageSpaces() const { return garage_spaces_; }
    // size_t getNumWheels() const { return num_wheels_; }
    // 然后在main中输出:
    // cout << "车库占用空间:" << c.getGarageSpaces() << endl;
    // cout << "车轮数量:" << c.getNumWheels() << endl;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:45:33