我試圖理解虛函數,並且遇到以下代碼。將派生類構造函數分配給基類指針
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