我有一個基類Device和繼承類InputDevice。在 XYZ 類中,我有一個函式XYZ::setDevice(int num, Device device),它期望物件 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());
}
uj5u.com熱心網友回復:
我沒有看到完整的代碼,但你應該存盤指標而不是存盤物件。您的設備陣列應該是向量或設備指標陣列。
這是一個完整的示例。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Device {
public:
virtual string getName() const {
return string("Device");
}
};
class InputDevice : public Device {
public:
string getName() const override{
return string("InputDevice");
}
};
class XYZ {
Device* devices[10];
public:
void setDevice(int num, Device *device)
{
devices[num] = device;
cout << "Name : " << device->getName();
}
};
int main()
{
Device* dev1 = new Device();
Device* dev2 = new Device();
InputDevice* dev3 = new InputDevice();
XYZ xyz;
xyz.setDevice(0, dev1);
xyz.setDevice(1, dev2);
xyz.setDevice(2, dev3);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/537506.html
標籤:C 哎呀遗产基类
