多态应用举例2
2015-08-25 11:40
375 查看
#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;
}
相关文章推荐
- 火狐浏览器打开新标签页为空白页
- JAVA并发编程5_线程状态
- shell编程实例---实现整数的加减乘除余运算(利用read和脚本传参的方式)
- 创建线程的两种方式比较Thread VS Runnable
- Tyvj P1015 公路骑 (DP)
- JAVA并发编程5_线程状态
- iOS 字体滚动效果 ScrollLabel
- native 方法列表说明
- excel转换成pdf的方法
- Leetcode -- Two Sum
- spring整合quartz持久化
- Java @注解
- 总结系列-触摸屏事件的传递机制
- 反转字符串
- OVER(PARTITION BY)函数用法
- 蓝牙4.0简介
- 哪个进程回复ICMP报文
- MyBatis的动态SQL详解
- Android listview 属性解析
- 关于cocos2dx如何绑定c++的静态方法和类给lua调用