c++ - 多态是实现这一目标的最佳方法吗? (关于派生类中的函数调用)

标签 c++ class object c++11 polymorphism

我有一个包含四个类的程序:

  • 车辆(基地)
  • 汽车(源自车辆)
  • 汽车(源自汽车)
  • 卡车(源自汽车)

在运行时,用户使用工厂函数生成一个汽车对象,该对象可以是“汽车”或“卡车”:

Automobile *Automobile::make_automobile(std::string choice) {
    if (choice == "car")
        return new Car;
    else if (choice == "truck")
        return new Truck;
    else
        return nullptr;
}

现在,“Car”类具有三个独特的 setter(以及三个匹配的 getter):

  • Set_NumDoors()
  • Set_SeatMaterial()
  • Set_Shape()

“Truck”类有一个唯一的 setter(和一个匹配的 getter):

  • Set_CargoWeight()

起初,这些函数只在它们自己的类中实现,但我无法在运行时调用它们,因为创建的对象是“汽车”对象。我已经使用具有本地覆盖的虚拟函数解决了这个问题。现在,“Automobile”类的所有四个函数(以虚拟形式)默认情况下不执行任何操作。但是,当在对象上调用时,本地覆盖会执行正确的功能。下面是一个示例,一切正常。

汽车类中的定义

std::string defaultStatement = "Function call is invalid on current object";
    virtual int set_seatMaterial(std::string choice){
        std::cout << defaultStatement << std::endl;
        return -1;
    }

在汽车类中覆盖

    int set_seatMaterial(std::string choice) override { // override virtual base
        if (choice == "leather" || choice == "cloth"){
            seatMaterial = choice;
            return 0;
        }
        else
            return -1;
    }

然后,我在 main() 中使用函数指针来适本地指向所需的函数:

if (user_choice == "seat"){
            std::function<int(Automobile*, std::string)> choiceFunction = &Automobile::set_seatMaterial;
            choiceFunction(userVehicle, seatMaterial);
}

我唯一的问题是 - 这是实现此功能的最佳方式吗?它可以工作,但现在我已经声明了“Automobile”类中的每个函数,该类已经有自己的 getter/setter 了。尽管我理解多态性的概念及其用处,但从某种意义上来说,这似乎是重复。

或者是否有更好的方法从基类对象调用派生类函数?

最佳答案

I have solved this issue using virtual functions with local overrides. So now, the "Automobile" class all four functions (in virtual form), which by default do nothing. However, when called on an object, the local override performs the correct functionality. Below is an example, and it all works.

这使得 Automobile 的实现者有必要了解从它继承的所有类提供的所有方法,这使得维护变得困难。

当您需要知道您正在处理的汽车类型时,另一种选择是dynamic_cast

C++11 示例:

Automobile* unknown = ...;

if(auto car = dynamic_cast<Car*>(unknown)) {
    // call car-specific methods
    car->Set_NumDoors(4);

} else if(auto truck = dynamic_cast<Truck*>(unknown)) {
    // call truck-specific methods
    truck->Set_CargoWeight(1000);
}

Demo

关于c++ - 多态是实现这一目标的最佳方法吗? (关于派生类中的函数调用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65477269/

相关文章:

c++ - QImage::operator== 可以为具有相同内容的图像返回 false

class - JAX-WS - Web 服务生成的类在哪里?

java - 为什么分配刚刚声明的类变量是非法的?

javascript - 如何在自定义Object.prototype.xxx函数中获取对象本身?

java - 检查 java List<object> 对象类型

c++ - 使用 typedef 时可以重命名成员吗?

c++ - 如何使用 std::copy 将一个 constexpr 数组复制到另一个 constexpr 数组?

c++ - 用模板复制构造函数替换默认复制构造函数

java - 将 double 型转换为浮点型

java - 使用GSON解析JSON数组和对象