我有以下示例代码:
#include <iostream>
#include <string>
using namespace std;
class Event
{
public:
string type;
string source;
};
class KeyEvent : public Event
{
public:
string key;
string modifier;
};
class MouseEvent : public Event
{
public:
string button;
int x;
int y;
};
void handleEvent(KeyEvent e)
{
if(e.key == "ENTER")
cout << "Hello world! The Enter key was pressed ;)" << endl;
}
Event generateEvent()
{
KeyEvent e;
e.type = "KEYBOARD_EVENT";
e.source = "Keyboard0";
e.key = "SPACEBAR";
e.modifier = "none";
return e;
}
int main()
{
KeyEvent e = generateEvent();
return 0;
}
我无法编译它,G++ 会抛出一个错误:
main.cpp: In function 'int main()':
main.cpp:47:29: error: conversion from 'Event' to non-scalar type 'KeyEvent' requested
我知道 C++ 大师的错误很明显,但我不明白为什么我不能从基类对象转换为派生对象。有人可以建议我解决我遇到的问题吗?谢谢你的建议