【发布时间】:2014-07-07 14:43:16
【问题描述】:
#include <iostream>
using namespace std;
class Person
{
public:
void P(){ cout << "Person P" << endl; }
virtual void Print(){ cout << "Person Print" << endl; }
Person(){ cout << "Constructor Person" << endl; }
virtual ~Person(){ cout << "Dectructor Person" << endl; }
};
class Developer : public Person
{
public:
void Pi() { cout << "Developer Pi" << endl; }
void Print() override
{
cout << "Developer Print" << endl;
}
Developer(){ cout << "Constructor Develoeper" << endl; }
~Developer(){ cout << "Dectructor Develoer" << endl; }
};
int main()
{
Person *p = new Person();
Developer* d = dynamic_cast<Developer*>(p);
d->Pi();
delete p;
delete d;
return 0;
}
输出:
Constructor Person
Developer Pi
Dectructor Person
为什么我可以调用Developer的函数Pi?
没有Developer的构造函数如何调用Pi?
请注意,Pi 仅在 Developer 类中声明。
【问题讨论】:
-
你可以做任何你想做的事,但这会导致未定义的行为
-
查看这个非常彻底的答案,了解为什么这是 UB:stackoverflow.com/a/2474021/3549027
标签: c++ inheritance