【问题标题】:Is in operator overloading the left side of the operator is implicitly passed to function?在运算符重载中,运算符的左侧是否隐式传递给函数?
【发布时间】:2019-12-07 10:53:14
【问题描述】:

我对 c++ 中的运算符重载有一些疑问。

#include<iostream>

using namespace std;


class ex
{
    int i;
public:
    ex(){}
    void operator+(ex ob);
    void seti(int x);
    int geti();
};

void ex::operator+(ex ob)
{
    this->i+=ob.i;
}

void ex::seti(int x)
{
    i=x;
}

int ex::geti()
{
    return i;
}

int main()
{
    ex ob1,ob2;

    ob1.seti(2);
    ob2.seti(2);

    ob1+ob2;

    cout<<"ob1:"<<ob1.geti();
    cout<<"\nob2:"<<ob2.geti();

    return 0;
}

输出:

ob1:4
ob2:2
Process returned 0 (0x0)   execution time : 0.400 s
Press any key to continue.

这里运算符 + 的左侧是 ob1 被隐式(this 指针)传递给函数,而 ob2 通过参数传递给函数我可以接受。

但是看下面的代码。

#include<iostream>

using namespace std;


class ex
{
    int i;
public:
    ex(){}
    void operator++();
    void seti(int x);
    int geti();
};

void ex::operator++()
{
    this->i++;
}

void ex::seti(int x)
{
    i=x;
}

int ex::geti()
{
    return i;
}

int main()
{
    ex ob1;

    ob1.seti(2);

    ob1++;

    cout<<"ob1:"<<ob1.geti();

    return 0;
}

当我在上面编译时显示此错误:

D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp||In function 'int main()':|
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp|37|error: no 'operator++(int)' declared 
for postfix '++' [-fpermissive]|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 2 second(s)) ===|

当我更改 ob1++ 行时;到++ob1;它将编译成功并显示结果3。

我的疑问是 In 运算符重载重载运算符的左侧被隐式(this 指针)传递给函数,但为什么这里不会发生这种情况。编译器说更改 ob1++ 行;像 ++ob1 这样的后缀;但正确的对象。

请帮帮我。

【问题讨论】:

标签: c++ operator-overloading


【解决方案1】:

这个成员函数

void operator++();

定义了一个预增运算符++,应该像这样声明和定义

ex & operator++();

和

ex & ex::operator++()
{
    this->++i;

    return *this;
}

后自增运算符的声明和定义可以是这样的

ex operator ++( int );

和

ex operator ++( int )
{
    ex obj = *this;
    i++;

    return obj;
}

因此编译器发出错误,因为在程序中使用了未为类 ex 声明和定义的后增量运算符。

当运算符是成员函数时,运算符的左操作数是函数的隐式参数*this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    • 2016-02-06
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多