近来阅读《Inside the C++ Object Model》,里边讲到,在C++中多态只存于public class体系中,且只有通过pointer和reference来间接处理。
#include <iostream> using std::cout; using std::endl; class Base { public: virtual void printf(void) { cout<< "Base printf"<< endl; } }; class Derv : public Base { public: virtual void printf(void) { cout<< "Derv printf"<< endl; } }; int main(int argc, char** argv) { Base* pBase = new Base(); Derv* pDerv = new Derv(); pBase = pDerv; pBase->printf(); cout<<"-------------------------"<< endl; Base* pBase2 = new Derv(); pBase2->printf(); cout<<"-------------------------"<< endl; Base base; Derv derv; base = derv; base.printf(); cout<<"-------------------------"<< endl; Derv derv2; Base &base2 = derv2; base2.printf(); getchar(); return 0; }
结果如下:
可见对象base并未调用派生类中的printf()函数,而是继续使用基类的函数。
不知在哪见过,调用printf()函数时,指向它的this指针属于谁,那么就调用谁的printf();具体内容待找到后补上。
例子:
#include <iostream> using std::cout; using std::endl; class Base { public: Base(): m_nData(1){} virtual void printf(void) { cout<< m_nData<< endl; } private: int m_nData; }; class Derv : public Base { public: Derv() : m_nData(2){} virtual void printf(void) { cout<< m_nData<< endl; } private: int m_nData; }; int main(int argc, char** argv) { Base* pBase = new Base(); Derv* pDerv = new Derv(); pBase = pDerv; pBase->printf(); cout<<"-------------------------"<< endl; Base* pBase2 = new Derv(); pBase2->printf(); cout<<"-------------------------"<< endl; Base base; Derv derv; base = derv; base.printf(); cout<<"-------------------------"<< endl; Derv derv2; Base &base2 = derv2; base2.printf(); getchar(); return 0; }
结果如下: