更新时间:2023-02-15 17:54:50
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.