【发布时间】:2022-11-16 06:32:40
【问题描述】:
在我的车辆基类中,我有一个私有成员变量,字符串类型(用于车辆类型,即汽车摩托车,三轮车。
#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 变量,该变量将被传递到它的构造函数中。我想根据 numberOfWheels 使用 bicicle 或 tricicle 类型初始化基类构造函数。
我不知道如何实现这一点,因为基类构造函数必须在子类的函数体之前初始化。下面显示了我想要实现的目标,(虽然我知道这是不可能的......)
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(){};
【问题讨论】:
-
你可以使用一个函数来初始化它:
bike::bike():vehicle(reg, make, model, age, tricOrBic(numOfWheels))和std::string tricOrBic(int numberOfWheels)。不确定是否有任何重复项。
标签: c++ inheritance constructor