【问题标题】:Redundancy in post-increment overloading?后增量重载的冗余?
【发布时间】: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


【解决方案1】:

您的后自增运算符重载示例是错误的。

工商局

// Passing dummy int argument is to mention overloading of post-increment  
MyIncrDecrClass& operator++(int)  
{ 
    this->m_nCounter++; 
    return *this; 
} 

应该有

// Passing dummy int argument is to mention overloading of post-increment  
MyIncrDecrClass operator ++( int )  
{
    MyIncrDecrClass tmp( *this );

    ++this->m_nCounter; 

    return tmp; 
}

另外,您的问题完全不清楚。您实际上定义了两次相同的运算符

VLongInt& VLongInt::operator++()
{
    //...
    return *this;
}

VLongInt& VLongInt::operator++()
{
    //...
    return *this;
}

我看不出有什么不同。此外,您没有显示您的类定义,因此对您的问题无话可说。未知。

至少正如您自己所说,您的后增量运算符应该使用int 类型的虚拟参数声明。它必须返回一个临时对象。

VLongInt  VLongInt::operator ++( int )

const VLongInt  VLongInt::operator ++( int )

【讨论】:

  • 对不起,应该是:VLongInt& VLongInt::operator++(int)
  • @user2967016 这是一个错误的声明,因为您返回了对象本身。因此,您的后增量和前增量运算符之间没有区别。
  • 好的,我应该这样做吗?这=原始; ... this->vec = temp ... 返回原来的????
  • 如果我返回原来的这个,会不会使它成为后增量?你能解释一下代码的内部工作吗? C++ 有点神秘。
  • @user2967016 后增量意味着您必须在更改其状态之前返回对象的副本。如果您返回 *this,那么您将返回已修改的对象。全部写在我的帖子中应该如何定义运算符。
【解决方案2】:

有什么问题吗?

是的,您的代码违反了 ODR(一个定义规则)。在 § 3.2/1 中定义为:

任何翻译单元都不得包含一个以上的任何变量、函数、类类型、枚举类型或模板的定义。

您应该改为定义这两个函数:

VLongInt& VLongInt::operator++();
const VLongInt VLongInt::operator++(int);

请特别注意,后自增运算符应返回const TTT 是您的类类型)。

【讨论】:

  • 这是真的有必要(可能会改变输出)还是我要成为专业程序员应该做的事情?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-21
  • 2019-09-17
  • 1970-01-01
相关资源
最近更新 更多