C++基类的指针

来源:互联网 发布:淘宝宝贝隐形降权 编辑:程序博客网 时间:2024/06/14 18:31
#include <iostream>//基类的指针using namespace std;class Test//父类{protected:int height;int width;public:void setvalue(int a,int b){width=b;height=a;}};class Rectangle:public Test//子类{public:int area(){return(width*height);}};class Triangle:public Test//子类{public:int area(){return(width*height/2);}};void main(){Rectangle rect;//声明长方形类的对象Triangle tri;//声明三角形类的对象Test *test1=▭//声明一个父类的指针test1,并且指向长方形的地址,因为rect是Test的子类Test *test2=&tri;//声明一个父类的指针test2,并且指向三角形的的地址,因为tri是Test的子类test1->setvalue(3,4);//调用设置长和宽的功能函数test2->setvalue(4,5);//调用三角形设置底边和高的函数cout<<"正方形面积为:"<<rect.area()<<endl;//Test *只能引用从基类中继承来的成员,所以不能使用Test->area();cout<<"三角形面积为:"<<tri.area()<<endl;//Test *只能引用从基类中继承来的成员,所以不能使用Test->area();getchar();}

0 0