64,648
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
using namespace std;
//基类
class Tsharp
{
protected:
int height,width;
public:
Tsharp(const int h=0,const int w=0){height=h;width=w;};
virtual float area() = 0; //纯虚函数
};
//三角形类
class Ttriangle : public Tsharp
{
public:
Ttriangle(const int h,const int w):Tsharp(h,w){};
virtual float area(){return 0.5*height*width;};
};
//矩形类
class Trectangle : public Tsharp
{
public:
Trectangle(const int h,const int w):Tsharp(h,w){};
virtual float area(){return height*width;};
};
//计算数组长度的函数模板
template<typename T>
int getArrayLen(T &arr)
{
if(sizeof(arr) == 0)
return 0;
return sizeof(arr)/sizeof(arr[0]);
}
float totalArea(Tsharp *sharp[])
{
cout << *sharp << ".......*sharp" << endl;
cout << &sharp << ".......&sharp" << endl;
cout << sharp << ".........sharp" << endl << endl;
int arrayLength = getArrayLen(sharp);
float sum = 0;
for(int i = 0; i<arrayLength ; i++)
sum += sharp[i]->area();
return sum;
}
int main()
{
Tsharp *t1,*t2;
Trectangle rec(3,5);
Ttriangle tri(3,5);
t1 = &rec;
t2 = &tri;
cout << "长方形(3,5)面积: " << t1->area() << endl;
cout << "三角形(3,5)面积: " << t2->area() << endl;
cout << "--------------------------------\n";
Tsharp *s[2];
//cout << &s[1] << endl;
s[0] = &rec;
s[1] = &tri;
cout << s << ",,,,,,,,,s"<<endl;
cout << &s << ".........&s" << endl << endl;
cout << *s << "..........*s" << endl;
cout << s[0] << "........s[0]" << endl;
cout << &rec << ".........&rec" << endl << endl;
cout << "面积之和:" << totalArea(s) << endl;
getchar();
return 0;
}