这个不是很会,求帮助,急!

定义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;
}
  • Cat 数组定义6个,需要初始化 6个元素才行
  • 参考如下:

#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;
}