#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
中声明。
你可以做任何你想做的事情,但会导致**未定义的行为** – Rakib
请看这个非常全面的答案为什么这是UB:http://stackoverflow.com/a/2474021/3549027 – dlf