如何使const lvalue成为常量 [英] how to make const lvalue a constant

查看:82
本文介绍了如何使const lvalue成为常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const box& operator++()  //postfix
	{
		const box& b = *this;

		this->width++;
		this->height++;
		this->length++;

		return b;
	}





这是我的代码。但即使左值是一个常数,这也会显示递增的值。



这样可以毫无问题地完成..





here is my code. but this displays incremented values even if lvalue is a constant.

this can be done without problem like this..

box operator++()  //postfix
	{
		const box b = *this;

		this->width++;
		this->height++;
		this->length++;

		return b;
	}





但问题是我想用左值参考来做这件事。我的意思是我想要归还盒子和盒子没有增加价值的东西。



我该怎么办?



提前谢谢。



But the thing is I want to do this with lvalue references. I mean I want to return a "box&" thing without incrementing it's values.

How can I do it ?

Thanks in advance.

推荐答案

第二个版本是正确的,不应该更改!返回值必须是递增前实例的。该值只能是一个副本 - 如果它是一个左值并被修改,组合修改(带增量)的结果将是未定义的。



如果你想要修改和增加对象,要么在调用increment运算符之前进行修改(在单独的语句中),要么使用前缀增量。这样,修改的顺序是明确的。
The second version is correct and shouldn't be changed! The return value must be the value of the instance before incrementation. That value can only be a copy - if it were an lvalue and being modified, the result of the combined modification (with the increment) would be undefined.

If you want to modify as well as increment the object, either do the modification before calling the increment operator (in a separate statement), or use prefix increment. That way the order of modifications is unambiguous.


这篇关于如何使const lvalue成为常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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