#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();
}
C++基类的指针
最新推荐文章于 2023-11-08 10:30:00 发布