#include<iostream>
class Base{
public:
void fun1(){
this->fun2();//this 基类指针 fun2虚函数 所以是多态
}
virtual void fun2(){
cout <<"Base::fun2()"<<endl;
}
};
class Derived:public Base{
public:
virtual void fun2(){
cout<<"Derived::fun2()"<<endl;
}
};
int main(){
Derived d;
Base * pBase = &d;
pBase->fun1();//pBase ->fun1 this指针就是指向子类的对象 调用 子类fun2函数
return 0;
}
//得出结论 非构造函数,非析构函数的成员函数中调用虚函数就是多态
//在构造函数和析构函数中调用虚函数不是多态,在编译时候就可以确定,
//调用的函数是自己的类或基类中定义的函数,不会等到运行时候才决定调用是自己的还是派生类的函数
class myclass{
public:
virtual void hello(){
cout<<"hello from myclass"<<endl;
}
virtual void bye{
cout<<"bye from myclass"<<endl;
}
};
class son:public myclass{
public:
void hello(){//派生类中和基类中虚函数同名同参数表的函数 不加virtual 也自动成为虚函数
cout<<"hello from son"<<endl;
}
son(){
hello();
}
~son(){
bye();
}
};
class grandson:public son{
public:
void hello(){
cout<<"hello from grandson"<<endl;
}
void bye(){
cout<<"bye from grandson"<<endl;
}
grandson(){cout<<"constructing grandson"}
~grandson(){
cout<<"destructing grandson"<<endl;
}
};
int main(){
grandson gson;
son*pson;
pson= &gsion;
pson->hello();//多态
return 0;
}
class Base{
public:
void fun1(){
this->fun2();//this 基类指针 fun2虚函数 所以是多态
}
virtual void fun2(){
cout <<"Base::fun2()"<<endl;
}
};
class Derived:public Base{
public:
virtual void fun2(){
cout<<"Derived::fun2()"<<endl;
}
};
int main(){
Derived d;
Base * pBase = &d;
pBase->fun1();//pBase ->fun1 this指针就是指向子类的对象 调用 子类fun2函数
return 0;
}
//得出结论 非构造函数,非析构函数的成员函数中调用虚函数就是多态
//在构造函数和析构函数中调用虚函数不是多态,在编译时候就可以确定,
//调用的函数是自己的类或基类中定义的函数,不会等到运行时候才决定调用是自己的还是派生类的函数
class myclass{
public:
virtual void hello(){
cout<<"hello from myclass"<<endl;
}
virtual void bye{
cout<<"bye from myclass"<<endl;
}
};
class son:public myclass{
public:
void hello(){//派生类中和基类中虚函数同名同参数表的函数 不加virtual 也自动成为虚函数
cout<<"hello from son"<<endl;
}
son(){
hello();
}
~son(){
bye();
}
};
class grandson:public son{
public:
void hello(){
cout<<"hello from grandson"<<endl;
}
void bye(){
cout<<"bye from grandson"<<endl;
}
grandson(){cout<<"constructing grandson"}
~grandson(){
cout<<"destructing grandson"<<endl;
}
};
int main(){
grandson gson;
son*pson;
pson= &gsion;
pson->hello();//多态
return 0;
}