为什么==重载可以访问参数的私有成员 [英] Why == overloading can access private members of argument

查看:90
本文介绍了为什么==重载可以访问参数的私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么obj的私有值可以是是否由类实例更改了?

Possible Duplicate:
why private value of the obj can be changed by class instance?

考虑以下(部分)代码:

Consider the following (partial) code:

class Group {
    private:
      int id;

    public:
      void set_id(int);
      int get_id();
      bool operator==(const Group&);
};


bool Group::operator==(const Group& g) {
    if(g.id == this->id) {  /* id is private? */
            return true;
    }

    return false;
}

代码会编译,结果似乎正确.但是,在运算符重载实现的if部分中,我们直接访问其参数的私有成员-const Group& g,但这不是无效的访问吗?

The code compiles and results seem proper. However, in the if part of the operator overloading implementation, we are directly accessing the private member of its argument - const Group& g, but isn't such an access invalid?

推荐答案

您的operator==Group类的成员.成员函数可以访问该类的任何private成员,不仅可以访问this,而且可以访问任何实例.

Your operator== is a member of your Group class. Member functions can access any private members of that class, not only for this, but for any instance they can access.

如果考虑到此行为,则是必需的,因为否则访问控制将使两个或更多实例(swap,复制构造函数,运算符)的交互方法变得不可能,除非对象具有任何成员变量的公共访问器,在这种方法中使用.从设计的角度来看,通常这是不希望的.此外,这将使访问控制的标准更高(如果我只是简单地将该成员公开,则可以免除我的痛苦……").

If you think about it this behaviour is necessary, because otherwise access control would make methods for interaction of two or more instances (swap, copy constructors, operators) impossible, unless the object has a public accessor to any member variable, which is used in such a method. Often enough that isn't desirable from a design point of view. Furthermore it would raise the bar for access control to high ("if I simply make that member public, I can spare me the pain...").

总结这段代码是完全有效的(尽管与简单地使用return g.id == this->id;相比,我不明白为什么if是必要的)

Concluding this code is perfectly valid (although I don't see why the if is necessary, compared to simply using return g.id == this->id;)

这篇关于为什么==重载可以访问参数的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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