【问题标题】:Explicitly initalize abstract base class constructor with value determined by parameter of derived class constructor使用由派生类构造函数的参数确定的值显式初始化抽象基类构造函数
【发布时间】: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


【解决方案1】:

像这样?

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)
{
}

这是正常的编程,也许你有一些我没有看到的问题。

【讨论】:

    猜你喜欢
    • 2013-12-30
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    • 2018-07-16
    • 2018-07-21
    • 2014-07-02
    • 1970-01-01
    相关资源
    最近更新 更多