求教“返回左值的函数不能const”的意思?~~!!~~~

lovesi3344 2009-11-20 01:16:42
求教“返回左值的函数不能const”的意思?~~!!~~~
如何判断左值和返回左值??


原话出自
http://topic.csdn.net/u/20091118/21/791c2e55-cdf0-4231-9ba1-45ca1f853c6f.html 6楼
...全文
214 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
小函数 2011-02-11
  • 打赏
  • 举报
回复
一个函数用怎么返回对象?如果是返回内部对象的话直接用eax寄存器返回,这样的函数前面加const是没有任何意义的,因为编译器已经不让返回值成为一个左值了,他只是一个立即数而已.第二种情况是返回用户自定义对象,他是用一个临时量的this返回的,是通过内存而不是寄存器返回的,所以他可以是左值也可以是右值,加了const 就是要防止类似ro()=X(1);这样的赋值语句出现(其中X是一个类,ro返回一个X对象),还有类似deal(ro())这样的调用出现的时候,因为按值传递和按引用传递的语法是一样的,如果deal原型是void deal(X x)的话没问题,不会把ro()的返回值当左值的,但是如果是void deal(X & x)的话,编译器不允许用非const指针建立const指针,所以这样是不行的,必须是void deal(const X & x),函数前面家const也就这么多了......看到这个帖子的人希望能多讨论回复一起学习
小小攻城师 2009-11-20
  • 打赏
  • 举报
回复
1楼很强大 5楼也很强大
左值简单的理解就是只要能放到赋值符号左边 能被赋值的就是左值
你const一个左值,就是左值不能改变 不能改变 别人给他赋值的时候会出去
所以返回左值 是不能被const加以限制的
liang0356 2009-11-20
  • 打赏
  • 举报
回复
1楼的意思,也就是用在赋值表达式左边的叫左值,用在右边的叫右值,左值可以当作右值来用,但反过来不可以。中间就是一大段例子了。

一般情况下,函数返回的是一个临时对象,不能企图改变其值,当然也就不能用作左值了。要用作左值的话,通常的方法是返回引用,(引用返回的不要是函数中的局部对象,否则很危险,对此有的编绎器会报错,有的不会。)如果函数有 const 修饰的话,不知道 const 是在函数声明的第一个位置还是在参数表后面,但无论如何有的话那就表明返回的对象只能读,不能写,也就不能改,当然做不了左值,这时候会报错。
na2650945 2009-11-20
  • 打赏
  • 举报
回复
左值是变量。
可以赋值。
可以修改。
当然要const啦。
左值是可修改的。
等号左边的值。
右值是常量。
不可以修改。
等号右边的值。
macrojj 2009-11-20
  • 打赏
  • 举报
回复
返回的是左值 就是说可以被赋值的。当然不能是const 了。
lovesi3344 2009-11-20
  • 打赏
  • 举报
回复
晕,英文不好,翻译一下
mstlq 2009-11-20
  • 打赏
  • 举报
回复
lvalues and rvalues
An object is a contiguous region of storage. An lvalue is an expression that refers to such an object. The original definition of lvalue referred to an object that can appear on the left-hand side of an assignment. However, const objects are lvalues that cannot be used in the left-hand side of an assignment. Similarly, an expression that can appear in the right-hand side of an expression (but not in the left-hand side of an expression) is an rvalue. For example

#include <string>
using namespace std;
int& f();
void func()
{
int n;
char buf[3];
n = 5; // n is an lvalue; 5 is an rvalue
buf[0] = 'a'; // buf[0] is an lvalue, 'a' is an rvalue
string s1 = "a", s2 = "b", s3 = "c"; // "a", "b", "c" are rvalues
s1 = // lvalue
s2 +s3; //s2 and s3 are lvalues that are implicitly converted to rvalues
s1 = //lvalue
string("z"); //temporaries are rvalues
int * p = new int; //p is an lvalue; 'new int' is an rvalue
f() = 0; //a function call that returns a reference is an lvalue
s1.size(); //otherwise, a function call is an rvalue expression
}

An lvalue can appear in a context that requires an rvalue; in this case, the lvalue is implicitly converted to an rvalue. An rvalue cannot be converted to an lvalue. Therefore, it is possible to use every lvalue expression in the example as an rvalue, but not vice versa.

64,639

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧