函数参数为指针数组的问题。

poppopa poppopa 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
下面这个程序的计算结果是错误的,我想计算两个图形的面积之和(通过totalArea()这个函数),但是结果只是计算了一个的面积。
问题1:为什么在totalArea()里面调用getArraylen()计算指针数组的长度返回为1呢?(我期望是2)
问题2:调试的时候,为什么在totalArea()里面的sharp的数据类型变成了 Tsharp**?(我期望是Tshap*[2],和实参s一样)。

我有点乱。。。求教各位了


#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;
}
...全文
评论 4
收藏 已收藏
分享
返回顶部
poppopa
C++ 语言 65,214 成员 250,514 内容