访问同类对象的私有元素 [英] Access private elements of object of same class

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

问题描述

这是合法吗?如果没有,下面的代码是否允许这个?

Is this legal? If not, will the following code allow this?

class Foo
{
    friend class Foo;
}


推荐答案

Foo已经可以访问所有Foo成员。两个Foo对象可以访问对方的成员。

That's redundant. Foo already has access to all Foo members. Two Foo objects can access each other's members.

class Foo {
public:
  int touchOtherParts(const Foo &foo) {return foo.privateparts;}
private:
  int privateparts;
};

Foo a,b;
b.touchOtherParts(a);

上面的代码可以正常工作。 B将访问一个私人数据成员。

The above code will work just fine. B will access a's private data member.

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

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