在C++中,无论我在网上看到后缀递增运算符声明的例子,它总是声明为C++后缀递增运算符的常量返回类型
T& operator++(int);
,我相信这是一个后缀的正确语法增量,不是吗?
问题是,每当我声明后缀增量时,我用const
关键字声明返回类型,以便它变成左值。
请参见示例代码:
class AClass
{
int foo;
public:
AClass(void) : foo(0) {};
// Suffix increment operator
// Consider adding const to return type
/* const */ AClass operator++(int)
{
AClass cp(*this);
foo++;
return cp;
};
// Prefix increment operator
AClass& operator++()
{
foo++;
return *this;
};
};
int main(int argc, const char* args[])
{
/* This code would fail to compile.
int bar = 5;
(bar++)++;
*/
// Similarily, I would expect this to fail
// but it will succeed unless I use const return type.
AClass a;
(a++)++;
}
我从未有过这样一个常量声明的运营商的问题,我知道它已经救了我们的代码从一个笨拙的同事做了一个错误。所以,我的问题是:
- 是否有任何缺点这样的做法?这确实是一个好习惯吗?
- 什么是后缀运算符的真正正确的声明(我的意思是标准)?
- 如果这不是标准的规定,但已经是一个很好的做法,它不应该成为一个标准吗?
非常感谢您的回答!
你的前缀运算符应该返回一个引用:'AClass&operator ++()' – avakar
II不能想到任何理由修改该函数的返回结果....我认为你很好。 –
谢谢,你是对的,已经纠正了这一点,但它并没有改变这个问题。 – Andrew