a**********2 发帖数: 340 | 1 class A
{
int x;
public:
A(int x_):x(x_){}
int& getX(){return x;}
};
A a1(10);
A a2(10);
int& y = a1.getX();
y = a2.getX();
y = 20;
a1和a2中的结果分别是什么?
第一个改变了
第二个没改变
什么原因? |
l******l 发帖数: 66 | 2 int& y = a1.getX(); this one is reference variable initialization, make y
the reference to a1.x.
y = a2.getX(); is just assignment, make a1.x = a2.x
y = 20; another assignment, make a1.x = 20. |
a**********2 发帖数: 340 | 3 哦,有道理,简单概念没弄清,多谢
【在 l******l 的大作中提到】 : int& y = a1.getX(); this one is reference variable initialization, make y : the reference to a1.x. : y = a2.getX(); is just assignment, make a1.x = a2.x : y = 20; another assignment, make a1.x = 20.
|
r*******y 发帖数: 1081 | 4 I think there would have been compiler error here since it is trying
to change a private member through reference.
But I run this and it is ok.
So we can not change a private member directly but we can
change the private member through reference or pointer.
【在 a**********2 的大作中提到】 : class A : { : int x; : public: : A(int x_):x(x_){} : int& getX(){return x;} : }; : A a1(10); : A a2(10); : int& y = a1.getX();
|
m********l 发帖数: 4394 | 5 yea, that's why the stupid '&' was invented.
that's the design of C++, encapsulation is to hide code from OTHER code,
not the programmer.
Same logic applies to 'friend'
【在 r*******y 的大作中提到】 : I think there would have been compiler error here since it is trying : to change a private member through reference. : But I run this and it is ok. : So we can not change a private member directly but we can : change the private member through reference or pointer.
|
m********l 发帖数: 4394 | 6 你试下这个:
class A
{
int x;
public:
A(int x_):x(x_){}
int& getX(){return x;}
};
A a1(11);
A a2(10);
int& y = a1.getX();
cout << y;
y = a2.getX();
cout << y;
y = 20;
cout << y;
看看结果是啥.
y = a2.getX() 是10吗?
is this the case why reference variable can't be reassigned to a new
reference?
【在 a**********2 的大作中提到】 : 哦,有道理,简单概念没弄清,多谢
|
r*******y 发帖数: 1081 | 7 I like reference. pointer is too complicated
【在 m********l 的大作中提到】 : yea, that's why the stupid '&' was invented. : that's the design of C++, encapsulation is to hide code from OTHER code, : not the programmer. : Same logic applies to 'friend'
|
b*******8 发帖数: 37364 | |