题目:用C++定义Boat与Car两个类,二者都有weight属性,定义二者的一个友元函数totalWeight(),计算二者的重量和
我的见解:网上很多人解答出来但他们把weight定义在public中我觉得没意义,友元函数是访问私有变量的。。
我的代码:#include"iostream"
using namespace std;
class Car;
class Boat
{
private:
double weight;
friend double totalweight(Boat&boat,Car&car);
public:
double goin1(double a)
{
weight=a;
return 1;
}
};
class Car
{
private:
double weight;
friend double totalweight(Boat&boat,Car&car);
public:
double goin2(double b)
{
weight=b;
return 1;
}
};
double totalweight(Boat&boat,Car&car)
{
return( Boat::weight)+(Car::weight);
}
int main()
{
double a,b,c;
cout<<"请输入Car,Boat重量"<<endl;
cin>>a>>b;
Boat A;
Car B;
A.goin1(a);
B.goin2(b);
cout<<"总重量为:"<<totalWeight(boat,car)<<endl
}
这是我写的麻烦各位大大帮我看一下。。。
编译出错:1.(VC2008): error C2597: 对非静态成员“Boat::weight”的非法引用
1>e:\c++\盒子类\盒子类\实现2.cpp(32) : error C3867: “Boat::weight”: 函数调用缺少参数列表;请使用“&Boat::weight”创建指向成员的指针
1>e:\c++\盒子类\盒子类\实现2.cpp(32) : error C2597: 对非静态成员“Car::weight”的非法引用
1>e:\c++\盒子类\盒子类\实现2.cpp(32) : error C3867: “Car::weight”: 函数调用缺少参数列表;请使用“&Car::weight”创建指向成员的指针
1>e:\c++\盒子类\盒子类\实现2.cpp(32) : error C2568: “+”: 无法解析函数重载
1> 无法从以前的错误中恢复;正在停止编译
2.(VC++6.0):ar and boat.cpp
c:\c++\car and boat.cpp(32) : error C2597: illegal reference to data member 'Boat::weight' in a static member function
c:\c++\car and boat.cpp(32) : error C2597: illegal reference to data member 'Car::weight' in a static member function
c:\c++\car and boat.cpp(32) : error C2568: '+' : unable to resolve function overload
c:\c++\car and boat.cpp(44) : error C2065: 'totalWeight' : undeclared identifier
c:\c++\car and boat.cpp(44) : error C2065: 'boat' : undeclared identifier
c:\c++\car and boat.cpp(44) : error C2065: 'car' : undeclared identifier
c:\c++\car and boat.cpp(45) : error C2143: syntax error : missing ';' before '}'
c:\c++\car and boat.cpp(45) : warning C4508: 'main' : function should return a value; 'void' return type assumed
执行 cl.exe 时出错.
car and boat.obj - 1 error(s), 0 warning(s)
我苦想了几个小时未果 临近崩溃请教各位大大贡献我所有积分33