同一类的对象可以访问彼此的私有数据 [英] Objects of the same class to access each other's private data

查看:65
本文介绍了同一类的对象可以访问彼此的私有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我想知道是否有办法让两个相同的

类的对象能够互相访问''私人数据,如下:


A级{

公开:

无效访问(const A& a){cout< ;<" a.value中= QUOT;<< a.value中<< ENDL; }

私人:

int value;

};


当然有明显的将价值公之于众的解决方案,但是我不想这么多......


干杯,

Manolis

Hi,

I was wondering if there is any way to make two objects of the same
class to be able to access each other''s private data, like this:

class A {
public:
void access( const A& a ) {cout<<"a.value="<<a.value<<endl; }
private:
int value;
};

There is of course the obvious solution to make the value public, but I
don''t like that too much...

Cheers,
Manolis

推荐答案

为什么不尝试编译并运行它?!

Why don''t you just try to compile and run it?!


是的,当然我已经尝试过了;它不起作用。


我刚刚找到了解决方案。这是(以防其他人

也想要它):


A级{

public:

int add(const A& b){return extaccess(* this,b); } $ / $
friend int extadd(const A& a,const A& b);

private:

int value;

};

int extadd(const A& a,const A& b)

{a.value + = b.value;返回a.value; }


如果有人有一个更好的解决方案(除了公开数据,或

让公众成员返回价值),请告诉我。


Manolis


__PPS__写道:
Yes, of course I''ve tried it; it doesn''t work.

I just found a solution actually. Here it is (just in case someone else
wants it too):

class A {
public:
int add(const A& b) { return extaccess(*this,b); }
friend int extadd(const A& a, const A& b);
private:
int value;
};
int extadd( const A& a, const A& b )
{ a.value += b.value; return a.value; }

If someone has a nicer solution (apart from making the data public, or
having a public member to return the value) please let me know.

Manolis

__PPS__ wrote:
为什么不尝试编译并运行它? !
Why don''t you just try to compile and run it?!



Manolis写道:
Manolis wrote:
是的,当然我已经尝试过了;它不起作用。
Yes, of course I''ve tried it; it doesn''t work.




它适用于我,因为它应该。您收到的错误消息是什么?


-


Pete Becker

Dinkumware,Ltd。( http://www.dinkumware.com


这篇关于同一类的对象可以访问彼此的私有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆