C++ 如何在继承的构造函数中传递基类构造函数的值

C++ 如何在继承的构造函数中传递基类构造函数的值,c++,class,inheritance,constructor,C++,Class,Inheritance,Constructor,我必须对car和vehicle进行分类,我试图使用参数化构造函数为car对象成员设置值,但它会给出错误 #include <iostream> #include <string> class vehicle { int wheels ; double price ; std::string color ; public: vehicle(int , double , std::string ) ; void initial

我必须对car和vehicle进行分类,我试图使用参数化构造函数为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;
}
#包括
#包括
等级车辆{
int车轮;
双倍价格;
字符串颜色;
公众:
车辆(整数、双精度、标准::字符串);
void初始化(int、double、std::string);
~车辆(无效);
};
车辆类别:公共车辆{
整数负载;
双倍重量;
公众:
汽车(整数,双,整数车轮,双价格,标准::字符串颜色);
void初始化(int,double,std::string,int,double);
~car(void);
};
汽车:汽车(整数负载,双倍重量,整数车轮,双倍价格,标准::字符串颜色):汽车(车轮,价格,颜色)
{
这个->加载=加载;
这个->重量=重量;
}
车辆::车辆(整数w,双p,标准::字符串c)
{
初始化(w,p,c);
}
无效车辆::初始化(整数w,双p,标准::字符串c)
{
车轮=w;
价格=p;
颜色=c;
}

它在car构造函数行中给出了一个错误

您必须显式调用基本构造函数,使用构造函数初始值设定项列表,您可以大大简化代码:

#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");
}
#包括
等级车辆{
int车轮;
双倍价格;
字符串颜色;
公众:
车辆(内部车轮,双倍价格,标准::字符串颜色):
轮子(轮子),价格(价格),颜色(颜色){}
};
车辆类别:公共车辆{
整数负载;
双倍重量;
公众:
汽车(整装,双倍重量,整型车轮,双倍价格,标准::字符串颜色):
车辆(车轮、价格、颜色)、负载(负载)、重量(重量){}
};
int main(){
c车(4,1500,4,36000,“白色”);
}

car::car(整数负载、双倍重量、发动机发动机)
--这与类中的声明不匹配。声明有6个参数——这也应该有6个参数。“它给出了错误”。有什么错误?德鲁·多尔曼。“car”的构造函数必须显式初始化基类“vehicle”,该基类没有默认构造函数且预期为“{”或“,(忽略定义未声明的构造函数的错误)此
car::car(int-load,double-weight,Engine-engi):vehicle(int-wheels,double-price,std::string-color)
错误。
car
的构造函数的初始化器列表需要将值传递给
vehicle
构造函数,例如
car::car(整数负载,双倍重量,发动机发动机):vehicle(4,10000,红色)
其中
4
表示车轮的数量,
10000
表示特定的价格,红色表示红色。@Peter我按照您所说的编辑了代码,它给了我相同的错误
car::car(整数负载,双倍重量,整数车轮,双倍价格,标准:字符串颜色):vehicle(车轮,价格,颜色)