在我的vehicle
基类中,我有一个私有成员变量string type
(用于车辆类型,即汽车,摩托车,三轮车等)。
#pragma once
using namespace std;
#include <string>
#include <iostream>
class vehicle {
public:
vehicle(string reg, string make, string model, int age, string type);
virtual ~vehicle() = default;
virtual double costPerDay() = 0;
protected:
int age;
int perDayCostCap(int costPD);
double penceToPounds(int pence);
private:
const string type;
string const reg, make, model;
};
其中一个派生类bike
有一个numberOfWheels
变量,该变量将传递给它的构造函数。我想初始化基类构造函数类型为bicycle
或tricycle
,具体取决于numberOfWheels
。
我不知道如何实现这一点,看到基类构造函数必须在子类的函数体之前初始化。
下面显示了我想要实现的目标(尽管,我知道这是不可能的):
bike::bike(int engineCC, int numOfWheels, string reg, string make, string model, int age)
:engineCC(engineCC), numOfWheels(numOfWheels) {
string tricOrBic = (numOfWheels == 2) ? "bicicle" : "tricicle";
vehicle:reg=reg, make=make, model=model, age=age, type=tricOrBic;
};
像这样?
bike::bike(int engineCC, int numOfWheels, string reg, string make, string model, int age)
: vehicle(reg, make, model, age, numOfWheels == 2 ? "bicycle" : "tricycle")
, engineCC(engineCC)
, numOfWheels(numOfWheels)
{
}
这是正常的编程,也许你有什么问题我没有看到。