定义Cat类,有weight属性,定义一个友元函数getTotalWeight(),计算一组Cat对象的重量和。请上传源程序文件及运行结果截图。
int main()
{
Cat mycat[6] = { Cat(1.1), Cat(2.2),Cat(3.3),Cat(4.4),Cat(5.5)};
cout << "Total weight:"<6) << endl;
return 0;
}
#include <iostream>
using namespace std;
class Cat {
public:
Cat(double w) : weight(w) {}
friend double getTotalWeight(Cat cats[], int size);
private:
double weight;
};
double getTotalWeight(Cat cats[], int size) {
double totalWeight = 0;
for (int i = 0; i < size; i++) {
totalWeight += cats[i].weight;
}
return totalWeight;
}
int main() {
Cat mycat[6] = { Cat(1.1), Cat(2.2), Cat(3.3), Cat(4.4), Cat(5.5) };
cout << "Total weight: " << getTotalWeight(mycat, 5) << endl;
return 0;
}
#include<iostream>
using namespace std;
class Cat
{
public:
Cat(double weight)
{
this->weight = weight;
}
friend double getTotalWeight(Cat cats[], int num);
private:
double weight;
};
double getTotalWeight(Cat cats[], int num)
{
double sum = 0;
for (int i=0; i < num; i++)
{
sum += cats[i].weight;
}
return sum;
}
//主程序
int main(void){
Cat mycat[6] = { Cat(1.1), Cat(2.2),Cat(3.3),Cat(4.4), Cat(5.5), Cat(6.6)};
cout << "Total weight:"<<getTotalWeight(mycat, 6) << endl;
return 0;
}