| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 523 人关注过本帖
标题:[求助]有关友元函数访问私有成员的问题
只看楼主 加入收藏
linhua86
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2006-4-8
收藏
 问题点数:0 回复次数:1 
[求助]有关友元函数访问私有成员的问题

一段有关友元函数的程序

#include<iostream.h>


class boy
{
int num;
public:
void set_num();

friend int get_total();
};

void boy::set_num()
{
cin>>num;
}

class girl
{
int num;
public:
void set_num()
{cin>>num;}
friend int get_total();
};

int get_total(boy a,girl b)
{
return a.num+b.num;
}

void main()
{
boy a;
girl b;
a.set_num();
b.set_num();
cout<<get_total(a,b);
}

--------------------Configuration: opp3 - Win32 Debug--------------------
Compiling...
opp3.cpp
D:\Program Files\Microsoft Visual Studio\MyProjects\opp3\opp3.cpp(29) : error C2248: 'num' : cannot access private member declared in class 'boy'
D:\Program Files\Microsoft Visual Studio\MyProjects\opp3\opp3.cpp(6) : see declaration of 'num'
D:\Program Files\Microsoft Visual Studio\MyProjects\opp3\opp3.cpp(29) : error C2248: 'num' : cannot access private member declared in class 'girl'
D:\Program Files\Microsoft Visual Studio\MyProjects\opp3\opp3.cpp(20) : see declaration of 'num'
Error executing cl.exe.

opp3.obj - 2 error(s), 0 warning(s)

为什么友元函数不能访问类的私有成员。
用c++ builder也编译不了,请问是哪里错了。谢谢

搜索更多相关主题的帖子: 函数 成员 访问 
2006-05-11 10:20
linhua86
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2006-4-8
收藏
得分:0 

已经明白错在哪里了,谢谢大家,
#include<iostream.h>

class girl;

class boy
{
int num;
public:
void set_num();

friend void get_total(boy,girl);
};

void boy::set_num()
{
cin>>num;
}

class girl
{
int num;
public:
void set_num()
{cin>>num;}
friend void get_total(boy,girl);
};

void get_total(boy a,girl b)
{
cout<<a.num+b.num;
}

void main()
{
boy a;
girl b;
a.set_num();
b.set_num();
get_total(a,b);
}

2006-05-11 10:47
快速回复:[求助]有关友元函数访问私有成员的问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015545 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved