当我从公共成员函数返回引用时,为什么我可以公开私有成员?

Mah*_*esh 10 c++ function return-type

在代码片段中,我能够访问类范围之外的私有成员变量.虽然不应该这样做,为什么在这种情况下允许?通过引用接收返回的私有变量是不好的做法?

#include <iostream>
#include <cstdlib>

class foo
{
    int x;
    public:
        foo(int a):x(a){}
        int methodOne() { return x; }
        int& methodTwo() { return x; }
};

int main()
{
    foo obj(10);
    int& x = obj.methodTwo();
    x = 20;              // With this statement, modifying the state of obj::x

    std::cout << obj.methodOne();
    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

关于这种方法,返回类型传达了什么?而且我什么时候应该有这种类型的返回类型?

int& methodTwo() { return x; }
Run Code Online (Sandbox Code Playgroud)

PS:如果主题行含糊不清,我很抱歉.有人可以将其更改为与此处相关的内容.谢谢.

Bil*_*eal 19

private并不意味着"此内存只能由成员函数修改" - 这意味着"直接尝试访问此变量将导致编译错误".当您公开对象的引用时,您已经有效地公开了该对象.

通过引用接收返回的私有变量是不好的做法?

不,这取决于你想要什么.std::vector<t>::operator[]如果他们无法返回非const引用,那么实现起来会非常困难:)如果您想要返回引用并且不希望客户端能够修改它,只需将其作为const引用即可.


Don*_*alo 5

返回私有成员作为引用是完全有效的,编写类的程序员有责任仔细选择是否允许这样做。此链接给出了何时可以完成此操作的示例。