C ++传递引用类的私有变量 - 编译器问题? [英] C++ passing reference to class' private variable - compiler issue?

查看:151
本文介绍了C ++传递引用类的私有变量 - 编译器问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过引用一个类中的私有变量传递是否可以直接改变该类可接受的实践?




$ b

例如:

// ------------------------------------------ -
class Others
{
public:
Others(){};
void ChangeIt(string& str){str =Changed by Others; }
};

// ---------------------------------------- ---
class Locals
{
private:
string PrivateString;
public:
Locals(){PrivateString =Set by Locals; };
void VisitOthers(){其他o; o.ChangeIt(PrivateString); }
const string GetString(){return PrivateString; }
};

// ---------------------------------------- ---
int main(void)
{
Locals lo;
cout<< lo.GetString()<< \\\
;
lo.VisitOthers();
cout<< lo.GetString()<< \\\
;
return 0;
}

输出:

 由本地设置
由其他人更改

需要做这样使用其他/不同的对象,私有的所有者类,但需要时可以由其他人改变。最后我想要的是这种做法回来,



基本上我担心的是,我想查看类/ struct基本上是一个缓冲区的指针,成员的地址作为到这个缓冲区的偏移,所以即使你传递一个成员的指针值,它将是没有它所属的类/结构的基指针是无用的。这是我本能地感觉到的情况,所以上面的例子甚至不可能。

解决方案

以防止,您通过参考传递您的私人成员。你调用的函数不是访问你的私有成员,它正在改变它自己的参数(恰好是一些类的成员)。代码是确定的,但重要的是,你调用的函数不会引用你的私有成员。


Is the passing by reference of a private variable in a class to be directly changed outside that class acceptable practice? Or is this something that the compiler 'should' pick up and prevent?

Example:

//-------------------------------------------
class Others
{
public:
 Others() {};
 void ChangeIt(string &str) { str = "Changed by Others"; }
};

//-------------------------------------------
class Locals
{
private:
 string PrivateString;
public:
 Locals() { PrivateString = "Set by Locals"; };
 void VisitOthers() { Others o; o.ChangeIt(PrivateString); }
 const string GetString() { return PrivateString; }
};

//-------------------------------------------
int main(void)
{
 Locals lo;
 cout << lo.GetString() << "\n";
 lo.VisitOthers();
 cout << lo.GetString() << "\n";
 return 0;
}

Output:

Set by Locals
Changed by Others

I need to do something like this using other/different objects, private to the owner class, but changeable by others when needed. Last thing I want is for this kind of practice to come back & byte me in the future.

What is essentially worrying me, is that I would like to view the class/struct as basically a pointer to a buffer, and the member's address as offsets into this buffer, so that even if you pass the pointer-value of a member it would be useless without the base-pointer of the class/struct to which it belongs. This is what I instinctively feel should be the case, so that the above example should not even be possible.

解决方案

There is nothing to prevent, you pass your private member by reference. The function you are calling isn't accessing your private member, it is changing it's own argument (that happens to be the member of some class). The code is OK, but the important thing is that the function you called doesn't keep a reference to your private member.

这篇关于C ++传递引用类的私有变量 - 编译器问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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