当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c++虚函数例子解析

c++虚函数例子解析

2020年04月03日  | 移动技术网IT编程  | 我要评论

marco和孙丹菲,太湖县天气预报,红小豆的作用

#include <iostream>
using namespace std;
class shape
{
public:
//普通函数前加virtual,普通函数变成了虚函数,=0表示抽象虚函数,子类必须实现该函数 virtual void printarea()=0; void hello(){cout<<"shape hello function"<<endl;}; }; class circle:public shape { public: circle(int a):r(a){} void hello(){cout<<"circle hello function"<<endl;}; void printarea(){cout<<"圆形面积为:"<<r*r*3.14<<endl;} private: int r; }; class rectangle:public shape { public: rectangle(int a,int b):x(a),y(b){} void hello(){cout<<"rectangle hello function"<<endl;}; void printarea(){cout<<"矩形面积为:"<<x*y<<endl;} private: int x; int y; }; class square:public shape { public: square(int a):l(a){} void hello(){cout<<"square hello function"<<endl;}; void printarea(){cout<<"正方形面积为:"<<l*l<<endl;} private: int l; }; void prints(shape *s) {
  //基类指针s指向子类对象
//s调用的函数printarea是虚函数,所以会调用子类的printarea s->printarea();
//s调用的函数hello不是虚函数,所以只会调用基类的hello s->hello(); } int main() { circle a(1); prints(&a); square b(2); prints(&b); rectangle c(1,2); prints(&c); return 0; }

 

输出:

圆形面积为:3.14
shape hello function
正方形面积为:4
shape hello function
矩形面积为:2
shape hello function

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网