【发布时间】: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 这样的后缀;但正确的对象。
请帮帮我。
【问题讨论】: