Derived d; Base *p = &d; p->Base::func();如果在派生类中的函数定义的时候想要调用基类的同名函数那么也要这样显式的调用,否则会引发无穷递归。
class Base{ public: virtual Base& operator =(Base& xx); } class Derived : public Base { public: virtual Derived& operator =(Base& xx); //virtual function Derived& operator =(Derived& xx); //real operator = }
//Base.h #pragma once #include <iostream> using namespace std; class Base { public: Base(void){ func();}; ~Base(void){ funp();}; virtual void func(){cout<<"this is in Base constructor"<<endl;} virtual void funp(){cout<<"this is in Base destructor"<<endl;}; };
//Derived.h #pragma once #include "base.h" class Derived : public Base { public: Derived(void){func();} ~Derived(void){func();} virtual void func(){cout<<"this is in Derived constructor"<<endl;} virtual void funp(){cout<<"this is in Derived destructor"<<endl;}; };
//main.cpp #include "Derived.h" void main() { Base X; Derived Y; }
//Base.h #pragma once #include <iostream> using namespace std; class Base { public: Base(void){ func();}; ~Base(void){ funp();}; virtual void func(){cout<<"this is in Base constructor"<<endl;} virtual void funp(){cout<<"this is in Base destructor"<<endl;}; virtual void fuck()=0; };
//Derived.h #pragma once #include "base.h" class Derived : public Base { public: Derived(void){func();} ~Derived(void){func();} virtual void func(){cout<<"this is in Derived constructor"<<endl;} virtual void funp(){cout<<"this is in Derived destructor"<<endl;}; virtual void fuck(){cout<<"what a fuck day it is!"<<endl;} };
//main.cpp #include "Derived.h" void main() { Derived Y; Base& X = Y; }
C++primer读书笔记11-多态,布布扣,bubuko.com
原文地址:http://blog.csdn.net/ddupd/article/details/38137301