我试图理解虚函数,并且遇到以下代码。将派生类构造函数分配给基类指针
class Base
{
public:
void Method1() { std::cout << "Base::Method1" << std::endl; }
virtual void Method2() { std::cout << "Base::Method2" << std::endl; }
};
class Derived : public Base
{
public:
void Method1() { std::cout << "Derived::Method1" << std::endl; }
void Method2() { std::cout << "Derived::Method2" << std::endl; }
};
Base* obj = new Derived();
// Note - constructed as Derived, but pointer stored as Base*
obj->Method1(); // Prints "Base::Method1"
obj->Method2(); // Prints "Derived::Method2"
到底,如何用派生类构造函数初始化一个基类指针?
相关:http://stackoverflow.com/questions/4937180/a-base-class-pointer-can-point-to-a-derived-class-object-why-is-the-vice-versa – NathanOliver