【问题标题】:how to pass values for the base class constructor in the inherited constructor如何在继承的构造函数中为基类构造函数传递值
【发布时间】:2021-08-13 20:21:56
【问题描述】:

我必须对汽车和车辆进行分类我正在尝试使用参数化构造函数来设置 Car 对象成员的值,但它会给出错误

#include <iostream>
#include <string>
class vehicle {
    int wheels ;
    double price ;
    std::string color ;
    
public:
    vehicle(int , double , std::string ) ;
    void initialize (int , double , std::string ) ;
    ~vehicle (void) ;
};

class car : public vehicle {
    int load ;
    double weight ;
    
public:
    car (int , double  , int wheels , double price , std::string color ) ;
    void initialize (int , double , std::string , int , double ) ;
    ~car (void) ;
};
car::car(int load , double weight , int wheels , double price , std::string color ):  vehicle (wheels ,price , color )
{
    this->load = load ;
    this->weight = weight ;
}
vehicle::vehicle(int w,double p,std::string c)
{
    initialize(w,p,c);
}
void vehicle::initialize(int w,double p,std::string c)
{
    wheels = w;
    price = p;
    color = c;
}

它在汽车构造函数行中给出错误

【问题讨论】:

  • car::car(int load , double weight , Engine engi ) -- 这与类中的声明不匹配。声明有 6 个参数——这也应该有 6 个参数。
  • “它给出了错误”。有什么错误?
  • 德鲁·多尔曼。 'car' 的构造函数必须显式初始化没有默认构造函数的基类 'vehicle' 和预期的 '{' 或 ',
  • 另外(忽略定义未声明的构造函数的错误)这个car::car(int load , double weight , Engine engi ): vehicle (int wheels ,double price , std::string color ) 是错误的。 car的构造函数的初始化列表需要给vehicle构造函数传值,比如car::car(int load , double weight , Engine engi ): vehicle (4 , 10000, RED )其中4代表轮子数量,10000代表特定价格,RED指定红色.
  • @Peter 我按照你说的编辑了代码,它给了我同样的错误car::car(int load , double weight, int wheels , double price, std::string color ) : vehicle ( wheels , price , color )

标签: c++ class inheritance constructor


【解决方案1】:

你必须显式调用你的基本构造函数,并且使用构造函数初始化列表可以大大简化你的代码:

#include <string>
class vehicle {
    int wheels ;
    double price ;
    std::string color ;
    
public:
    vehicle(int wheels, double price, std::string color) : 
        wheels(wheels), price(price), color(color){}
};

class car : public vehicle {
    int load ;
    double weight ;
    
public:
    car (int load, double weight , int wheels, double price, std::string color ) : 
        vehicle(wheels, price, color), load(load), weight(weight){}
};

int main() {
    car c(4, 1500, 4, 36000, "white");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多