为什么当我从公共成员函数返回引用时暴露私有成员? [英] Why can I expose private members when I return a reference from a public member function?

查看:230
本文介绍了为什么当我从公共成员函数返回引用时暴露私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  #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; //用这个语句,修改obj :: x $ b的状态
$ b std :: cout<< obj.methodOne();
getchar();
return 0;
}

对于这种方法,返回类型传达什么?还有什么时候应该有这种返回类型?

  int& methodTwo(){return x; } 

PS:如果主题行模糊,有人可以将其更改为与此相关的内容。谢谢。

解决方案

private 并不表示此内存只能修改成员函数 - 意味着直接尝试访问此变量将导致编译错误。当你暴露对象的引用时,你已经有效地暴露了对象。


接收返回的私有变量参考?


不,这取决于你想要什么。如果 std :: vector< t> :: operator [] 如果不能返回非 - const 引用:)如果你想返回一个引用而不希望客户端能够修改它,只需使它成为一个 const 引用。 / p>

In the code snippet, I am able to access the private member variable outside the class scope. Though this should never be done, why is it allowed in this case? Is it a bad practice to receive a returned private variable by reference ?

#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;
}

And regarding this method, what does the return type convey ? And also when should I have return type of this kind ?

int& methodTwo() { return x; }

PS: I am sorry if the subject line is vague. Can someone change it to the content relevant here. Thanks.

解决方案

private does not mean "this memory may only be modified by member functions" -- it means "direct attempts to access this variable will result in a compile error". When you expose a reference to the object, you have effectively exposed the object.

Is it a bad practice to receive a returned private variable by reference ?

No, it depends on what you want. Things like std::vector<t>::operator[] would be quite difficult to implement if they couldn't return a non-const reference :) If you want to return a reference and don't want clients to be able to modify it, simply make it a const reference.

这篇关于为什么当我从公共成员函数返回引用时暴露私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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