【问题标题】:Passing objects of different derived class as a parameter to a function that expects base object of class将不同派生类的对象作为参数传递给需要类的基对象的函数
【发布时间】:2022-11-21 17:49:03
【问题描述】:

我有一个基类设备和继承类输入设备.在 XYZ 类中,我有一个函数XYZ::setDevice(int num, 设备设备)期望对象 Device 作为参数。当我使用作为 Device (InputDevice) 子类的参数调用函数 setDevice() 时,它被转换为 Device,之后我无法访问派生类的派生函数。 因此,如果我想在函数 setDevice() 中调用“设备”的函数,它会调用 Device 函数而不是类 InputDevice 中的重写函数。 我究竟做错了什么?

void XYZ::setDevice(int num, Device device) {

    printf("%s\n", typeid(device).name());                    //this prints "Device"
    this->devices[num] = device;
}

XYZ::XYZ() {
    printf("%s\n", typeid(InputDevice(cin)).name());          //this prints "InputDevice"

    setDevice(STANDARD_INPUT_DEVICE, InputDevice(cin));
    printf("%s\n", typeid(devices[0]).name());
}

【问题讨论】:

  • 更改void XYZ::setDevice(int num, Device device) {以参数为参考:void XYZ::setDevice(int num, Device& device) {
  • 这就是所谓的对象切片.根本问题不是setDevice,而是this->devices[num] = device;,它也会有相同的对象切片问题。您需要存储指向设备的指针(最好是智能指针,如std::unique_ptr<Device>)。

标签: c++ oop inheritance base-class


【解决方案1】:

当您将它传递给作为 Device 的函数时,编译器只知道 Device 类及其函数。您的函数参数应该是 InputDevice 指针,以便访问派生类的函数。

void XYZ::setDevice(int num, InputDevice *device) {

    printf("%s
", typeid(device)->name());                  
    this->devices[num] = *device;
}

你应该用对象的地址来调用它。

【讨论】:

  • 这样我就无法传入类 OutputDevice 的对象
  • 该代码现在是合法的,但显然没有解决 OP 问题,因为当您将对象分配给 devices 数组时,它们将遇到相同的问题,即 InputDevice 被转换为 Device
  • 我没有看到完整的代码,但你应该存储指针而不是存储对象。您的设备数组应该是向量或设备指针数组。
  • @brmRush 该评论应该是您的答案,而不是上面的代码。
猜你喜欢
  • 2014-09-26
  • 2013-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多