题目要求:
输入代码:
#include<iostream>
using namespace std;
class Shape
{
public:
virtual double area()const =0 ; //虚基函数
};
class Rectangle :public Shape
{
public:
Rectangle (double l,double w)
{
length=l;
weith=w;
}
double area()const;
private:
double length ,weith;
};
double Rectangle::area()const//const包含this指针,不能被修改的类成员函数
{
double S;
S=weith*length;
return S;
}
class Triangle:public Shape
{
public:
double area()const ;
Triangle (double w,double h)
{
Width=w;
height=h;
}
private:
double Width;
double height;
};
double Triangle::area()const
{
double S;
S=(Width*height)/2.0;
return S;
}
int main()
{
double a,b;
cin>>a>>b; //输入矩形的长和宽
Rectangle r(a,b);//建立Rectangle类对象r, 矩形长a宽b
Shape *s1=&r;
cout<<s1->area()<<endl;//输出矩形的面积
double w,h;
cin>>w>>h; //输入矩形的长和宽
Triangle t(w,h); //建立Triangle类对象t,三角形底边长w高h
Shape &s2=t;
cout<<s2.area();//输出三角形面积
return 0;
}
总结:
开始写程序时,并没有在虚基函数area()后加const常变量,因为这个知识点自己忽略了,后来问同学才明白了。知道了const在类函数中的用法
原文:http://blog.csdn.net/linhaiyun_ytdx/article/details/46400115