用C++定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和

#include<iostream>
#include<cmath>
using namespace std;
class Car;
class Boat
{
public:
int weight;
friend int totalWeight(Boat &boat, Car &car);
};

class Car
{
public:
int weight;
friend int totalWeight(Boat &boat, Car &car);
};

int totalWeight(Boat &boat, Car &car)
{
return boat.weight + car.weight;
}
int main()
{
Boat boat(10);Car car(10);
cout<<"The weight is: ";
cout<<totalWeight(boat,car)<<endl;
}
麻烦帮忙看看哪错了,谢谢

没定义构造函数阿!!别的没什么阿!改的如下!
#include <iostream>
#include<cmath>
using namespace std;
class Car;
class Boat
{
public:
int weight;
friend int totalWeight(Boat &boat, Car &car);
Boat(int a):weight(a){}
};

class Car
{
public:
int weight;
friend int totalWeight(Boat &boat, Car &car);
Car(int a):weight(a){}
};

int totalWeight(Boat &boat, Car &car)
{
return boat.weight + car.weight;
}
void main()
{
Boat boat(10);Car car(10);
cout<<"The weight is: ";
cout<<totalWeight(boat,car)<<endl;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-05-12
#include<iostream>
using namespace std;
class Car;
class Boat
{
private:
int Boatwe;
public:
Boat() //无参数构造函数
{
Boatwe=500;
}
friend int totalWeight(Boat &,Car &);//注意这里
};
class Car
{
private:
int Carwe;
public:
Car( ) //无参数构造函数

{
Carwe=300;
}
friend int totalWeight(Boat &,Car &);//注意这里
};
int totalWeight(Boat &x,Car &y)//注意这里
{

return x.Boatwe+y.Carwe;
}
int main()
{
Boat a;
Car b;
cout<<"总重量为"<<totalWeight(a,b)<<endl; //不是>>而是<<

return 0;
}