【发布时间】:2020-12-24 13:42:41
【问题描述】:
这段代码运行良好,但它应该有一个运行时错误,因为我没有实例化派生类对象。
#include <iostream>
using namespace std;
class Person {
public:
void walk() { cout << "person walking" << endl; }
};
class Employee :public Person {
public:
void work() { cout << "employee working" << endl; }
};
void main() {
Person* p = new Person();
Employee* e = static_cast<Employee*>(p);
e->work();// this is working - but why? it should fail at runtime
}
如果static_cast只转换指针,怎么可能调用子成员函数呢?
子节点在什么时候被实例化?
static_cast 也是实例化对象吗?
【问题讨论】:
-
"它应该在运行时失败" 为什么会这样?未定义的行为是未定义。这可能包括“根据某种定义似乎‘有效’。”
-
你的 main 应该返回
int,而不是void -
无效程序必须会产生运行时错误,这一定是最常见的新手假设之一。在一个公平的世界里是真的,但这个世界是不公平的,只有无效程序可能产生运行时错误。
-
现在将百万个
ints 数组添加到Employee,并尝试将其清零,看看效果如何,如果您有兴趣看到您的代码崩溃。 -
你的代码有内存泄漏,每个
new'd必须有delete。
标签: c++ pointers inheritance casting static-cast