注册 登录
编程论坛 C++教室

(出错)友元函数的调用

hxjtiger 发布于 2007-11-28 20:45, 1409 次点击
#include<iostream>
using namespace std;
class car;
class boat
{
public:
 
 boat(int nw=100)
 {
  w=nw;
 }
 friend int car::total(boat &p1,car &p2);
private:
 int w;
};
class car
{
public:
 
 car(int nw=50)
 {
  w=nw;
 }
    int total(boat &p1,car &p2)
 {
  return p1.w+p2.y ;
 }
private:
 int y;
};
void main()
{
 boat boat1(1000);
 car car1(2000);
 cout<<"totalweight is"<<car1.total(boat1,car1)<<endl;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
你们帮我看看,怎么是一个类中的函数成为另一个类的友元函数调用类中的私有数据????
3 回复
#2
quying2572007-11-29 13:58
刚刚调了一下
把声明friend int car::total(boat &p1,car &p2);
改为friend  car;
就好用了 可为什么上面的形式不行啊 到底错到哪了?
#3
无缘今生2007-11-29 16:51
friend int car::total(boat &p1,car &p2);
你搞清楚:你所用的total()是类car的友元,你写成car::total()就是说total()是car的成员函数,
前后不一致,当然不行啦。
#4
o0花生0o2007-11-29 23:54
你定义的友元函数是两个类的友元函数,必须要在两个类中声明,在类car中
 int  total(boat &p1,car &p2)之前要加上friend
在调用友元函数输出结果时,由于total是两个类的友元函数,所以输出语句应该为
cout<<"totalweight is"<<total(boat1,car1)<<endl;
1