查看单个帖子
  #11 (permalink)  
旧 2008-08-18
wqqafnd 的头像
wqqafnd wqqafnd 当前离线
高级会员
 
注册日期: 2004-10-08
帖子: 196
文章: 1
wqqafnd 正向着好的方向发展
发送 MSN 消息给 wqqafnd
默认 回复: 请问什么是左值?

左值,右值的概念是以人的经验习惯为基础的。
根据习惯,等号左边的的值,是被改变的值,是非const的;等号右边的值,是不被改变的,可以是const或非const。
但是在C++里这一切都不是绝对的,比如下面的代码:
C++ 代码:
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct A
  6. {
  7.     int x;
  8.     A(int k = 0):x(k){}
  9.     const A & operator =(A & x) const{
  10.         cout<<"operator =()\n";
  11.         ++x.x;
  12.         return *this;
  13.     }
  14. };
  15.  
  16. int main()
  17. {
  18.     const A c1(1),c2(2);
  19.     A m1(3),m2(4);
  20.     c1 = m2;            //operator =()
  21.     cout<<c1.x<<endl    //1
  22.         <<c2.x<<endl    //2
  23.         <<m1.x<<endl    //3
  24.         <<m2.x<<endl;   //5
  25. }
左值是const A,右值却需要是非const的,一切都看编码者怎么设计。
回复时引用此帖