C++ 增量后重载中的冗余?

C++ 增量后重载中的冗余?,c++,operator-overloading,operators,overloading,C++,Operator Overloading,Operators,Overloading,这就是post和pre-increment操作符的实现方式,但在我的例子中,我不能这样实现它,所以我就是这么做的: // The following operator++() represents overloading of pre-increment MyIncrDecrClass& operator++() { ++this->m_nCounter; return *this; } // Passing dummy int argument i

这就是post和pre-increment操作符的实现方式,但在我的例子中,我不能这样实现它,所以我就是这么做的:

// 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; 
} 
有什么问题吗?看来,两者应该以同样的方式实施。只有头文件应该不同,对吗

有什么问题吗

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

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

您应该定义这两个函数:

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;
}

具体地说,请注意,递增后运算符应该返回
const T
T
(类类型为
T

递增后运算符重载的示例是错误的

VLongInt& VLongInt::operator++();
const VLongInt VLongInt::operator++(int);
应该有

// 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; 
}
我看不出有什么不同。此外,您没有显示您的类定义,因此无法对您的问题进行任何说明。这是未知的

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

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

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


听起来你的代码很有效,你只是想知道你是否写错了。这可能更适合它,这取决于您希望增量运算符对您的类表示什么。但在我看来,这似乎是错误的——无论哪种方式,你的论点都应该被修改——但在一种情况下,你应该返回原始版本,而不是修改后的版本。在第二段代码中,您编写了两个具有相同名称、返回类型和参数的函数。也许我对C++的了解不多,但是编译器应该如何区分这两个定义?@ DavidGrayson——我的观点!在两个代码块中,都没有正确定义后缀增量。在这两种情况下,前缀和后缀增量都做相同的事情(或者,如果第二个块实际编译,它们会做相同的事情)。后缀增量应该返回旧值,而不是
*这个
。如果我想成为一名专业程序员,这真的是必要的(可能改变输出的事情)还是我应该做的事情?对不起,它应该是:VLongInt&VLongInt::operator++(int)@user2967016这是一个错误的声明,因为您返回了对象本身。所以在后增量和预增量操作符之间没有区别。好吧,我应该这样做?这是原创的。。。这个->向量=温度。。。返回原件???如果我返回原件,这会使其成为后增量吗?你能解释一下代码的内部工作原理吗?C++是一种神秘的东西。@ USER 29 67016 POST增量意味着你必须在改变对象的状态之前返回它的副本。如果返回*this,则返回已修改的对象。所有这些都写在我的文章中,我认为应该如何定义操作符。
VLongInt  VLongInt::operator ++( int )
const VLongInt  VLongInt::operator ++( int )