【发布时间】:2014-03-05 01:32:05
【问题描述】:
// The following operator++() represents overloading of pre-increment
MyIncrDecrClass& operator++()
{
++this->m_nCounter;
return *this;
}
// Passing dummy int argument is to mention overloading of post-increment
MyIncrDecrClass& operator++(int)
{
this->m_nCounter++;
return *this;
}
这就是 post 和 pre increment 运算符的实现方式,但在我的情况下,我不能真正实现它,所以这就是我所做的:
VLongInt& VLongInt::operator++()
{
... //BUILD TEMP vector
this->vec = temp;
return *this;
}
VLongInt& VLongInt::operator++(int)
{
this->vec = this.vec; //seems unnecessary
... //BUILD TEMP vector
this->vec = temp
return *this;
}
有什么问题吗?似乎两者都应该以相同的方式实现。只有头文件应该不同吧?
【问题讨论】:
-
听起来你的代码有效,你只想知道你是否写错了。这可能更适合codereview.stackexchange.com
-
这完全取决于您希望增量运算符为您的班级表示什么。但在我看来它是错误的——无论哪种方式,你的论点都应该被修改——但在一种情况下,你应该返回原始版本,而不是修改后的版本。而且您不区分函数签名 - 这甚至可以编译吗?
-
在第二个代码块中,您编写了两个具有相同名称、返回类型和参数的函数。可能我对C++了解不够,但是编译器应该如何区分这两个定义呢?
-
@DavidGrayson - 我的观点完全正确!
-
在您的两个代码块中,您都没有正确定义后缀增量。在这两种情况下,您的前缀和后缀增量都做同样的事情(或者如果您的第二个块实际编译,它们会做同样的事情)。后缀增量应该返回旧值,而不是
*this。
标签: c++ operator-overloading operators overloading