派生参数化ctor的C ++设置值[重复]
Posted
技术标签:
【中文标题】派生参数化ctor的C ++设置值[重复]【英文标题】:C++ setting value of derived parameterlized ctor [duplicate] 【发布时间】:2015-10-13 03:15:39 【问题描述】:大家好。我不知道如何为派生类 ctor 设置值。这是我的代码。我记得在我的课堂上有类似的东西。但我知道我们可以编写类似这样的构建 (xxx():yyy(),,,;)。 检查 main 的第二个对象。
#include <iostream>
using namespace std;
class vehicle
protected:
string brand;
int wheelNumber;
double maxSpeed=0;
public:
vehicle()cout<<"default ctor for vehicle"<<endl;
vehicle(string br1, int wn1, double ms1)
brand=br1; wheelNumber=wn1; maxSpeed=ms1;
void setbrand(string br)brand=br;
string getbrand(string br)return brand;
void setWN(int wn)wheelNumber=wn;
int getWN(int wn)return wheelNumber;
void setMaxS(double ms)maxSpeed=ms;
double getMaxS(double ms)return maxSpeed;
~vehicle()cout<<"dtor for vehicle."<<endl;
;
class car: public vehicle
private:
int numberOfDoors;
string fuelType;
public:
car()cout<<"default ctor for car"<<endl;
car(int nOD,string fT)numberOfDoors=nOD; fuelType=fT;
void setnOD(int nOD)numberOfDoors=nOD;
int getnOD(int nOD)return numberOfDoors;
void setfT(string fT)fuelType=fT;
string getfT(string fT)return fuelType;
void printFeatures()
cout<<endl;
cout<<"brand:"<<brand<<endl;
cout<<"wheelNumber:"<<wheelNumber<<endl;
cout<<"MaxSpeed:"<<maxSpeed<<endl;
cout<<"NumberOfDoors:"<<numberOfDoors<<endl;
cout<<"FuelType:"<<fuelType<<endl<<endl;
~car()cout<<"dtor for car."<<endl;
;
int main()
car *cc;
cc= new car;
cc->setbrand("bmw");
cc->setfT("diesel");
cc->setMaxS(333.25);
cc->setWN(4);
cc->setnOD(6);
cc->printFeatures();
delete cc;
car *xx;
xx= new car;
car(5,"gasoline"):vehicle("mercedes",4,489.12);//Part that i cant figure it out.
xx->printFeatures();
delete xx;
【问题讨论】:
【参考方案1】:您需要将其编码到构造函数中才能使其工作。当您从一个类派生时,该派生类的构造函数需要接受基构造函数及其自身构造的参数。
class Base
int foo;
public:
Base(int f) : foo(f) ;
;
class Derived : public Base
int bar;
public:
Derivced(int f, int b) : Base(f), bar(b)
^^^^^^^ ^^^^^^^^^
construct the base part constrcut the derived part
;
因此,对于您而言,car
的构造函数将变为:
car(string br1, int wn1, double ms1, int nOD,string fT) : vehicle(br1, wn1, ms1),
numberOfDoors(nOD),
fuelType(fT)
【讨论】:
非常感谢。这对我非常有用:D【参考方案2】:由于您分配的是派生类 car 的实例,因此它同时调用了两个 ctor。首先它将调用类“车辆”的ctor,然后调用“汽车”。 [阅读case继承调用ctor的顺序]
【讨论】:
我编辑了问题。目标是在 main 中使用构造函数设置值。 没有car(5,"gasoline"):vehicle("mercedes",4,489.12);
is a compiler error【参考方案3】:
ctor(...):base(...)
语法在定义派生类构造函数时使用,而不是在实例化对象时使用。所以把car
的构造函数改成这样:
car(int nOD,string fT, string br1, int wn1, double ms1): vehicle(br1, wn1, ms1)
numberOfDoors=nOD; fuelType=fT;
然后像这样实例化您的 car
对象:
xx= new car(5,"gasoline", "mercedes",4,489.12);
更好的是,利用 C++ 的成员初始化语法来定义您的构造函数:
vehicle(string br1, int wn1, double ms1)
:brand(br1), wheelNumber(wn1), maxSpeed(ms1)
// ...
car(int nOD,string fT, string br1, int wn1, double ms1)
: vehicle(br1,wn1, ms1), numberOfDoors(nOD), fuelType(fT)
【讨论】:
以上是关于派生参数化ctor的C ++设置值[重复]的主要内容,如果未能解决你的问题,请参考以下文章