过载++运算符

Overload ++ operator

本文关键字:运算符 过载      更新时间:2023-10-16

我第一次尝试处理运算符重载,我写了这段代码来重载++运算符,使类变量ix增加一。。它完成了任务,但编译器显示了以下警告:

警告1警告C4620:找不到的"operator++"后缀形式类型"tclass",使用前缀表单c:\users\ahmed\desktop\cppq\cppq.cpp 25

警告2警告C4620:找不到的"operator++"后缀形式类型"tclass",使用前缀表单c:\users\ahmed\desktop\cppq\cppq.cpp 26

这是我的代码:

class tclass{
public:
    int i,x;
    tclass(int dd,int d){
        i=dd;
        x=d;
    }
    tclass operator++(){
        i++;
        x++;
        return *this;
    }
};
int main() {
    tclass rr(3,3);
    rr++;
    rr++;
    cout<<rr.x<<" "<<rr.i<<endl;
    system("pause");
    return 0;
}

此语法:

tclass operator++()

用于前缀++(实际上通常被写成tclass &operator++()(。为了区分后缀增量,您添加了一个未使用的int参数:

tclass operator++(int)

此外,请注意前缀增量最好返回tclass &,因为结果可能在:(++rr).x之后使用。

再次注意,后缀增量如下所示:

tclass operator++(int)
{
    tclass temp = *this;
    ++*this;     // calls prefix operator ++
                 // or alternatively ::operator++(); it ++*this weirds you out!!
    return temp;
}

有两个++ operator。您定义了一个并使用了另一个。

tclass& operator++(); //prototype for    ++r;
tclass operator++(int); //prototype for  r++;

后增量和预增量有单独的重载。增加后版本的签名是operator++(int),而增加前版本的签名则是operator++()

您已经定义了operator++(),所以您只定义了预注册。但是,在类的实例上使用postincrement,因此编译器告诉它将使用对preincrement函数的调用,因为没有定义postincremetion。