【发布时间】:2014-03-05 21:14:37
【问题描述】:
我有一个关于运算符重载的问题。下面是我的示例代码。如果你能通读它,我的问题就在下面。
//class definition
class example
{
private:
int a ; // Defined in FeetInches.cpp
public:
void seta(int f)
{
a = f;
}
example operator + (const example &); // Overloaded +
int geta()
{
return a;
}
};
example example::operator + (const example &right)
{
example temp;
temp.a = a + right.a;
return temp;
}
//主要
#include "header" //this is the class definition above
#include <iostream>
using namespace std;
int main()
{
example r;
r.seta(1);
example s;
s.seta(1);
example t;
t = r + s;
t = r + 1; //if included it won't compile
t = 1 + r; //if included it won't compile
int x = t.geta();
cout << x;
cin.get();
return 0;
}
我了解当您尝试使用运算符重载将对象一起添加时,它们应该是相同的。
这是一个问题: 我最近看到该对象何时位于它编译的运算符的一侧,但当它位于另一侧时却没有。如:
t = r + 1; 它已编译。
t = 1 + r; 没有。
(我也知道在我的示例中这两种方式都不起作用,但更容易用代码来构建问题。)
当对象在运算符的一侧时,运算符重载如何编译,但在另一侧时不编译。
谢谢
【问题讨论】:
-
尝试使用
operator+:r.operator+(1)重写您的作业。换一种方式试试,你会从编译器的角度看到。 -
这就是为什么他们经常建议将
operator+=实现为成员函数,然后将operator+实现为全局函数。这样,隐式转换可以发生在+运算符的左侧或右侧。