我有个关于操作员超载的问题。下面是我的示例代码。如果你能读懂,我的问题在下面。
//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;,它没有。
(我也知道,在我的示例中,这两种方法都不起作用,只是更容易用代码来构建问题。)
当对象位于操作符的一边时,操作符重载是如何编译的,而当对象位于另一边时,操作符重载是如何编译的。
谢谢
发布于 2014-03-05 21:33:07
如果t = r + 1;定义了匹配的operator+()方法,则意味着t = r.operator+(1);,否则就意味着t = operator+(r, 1);。它没有编译,因为您没有定义任何+操作符,这些操作符的左边是example,右边是int,例如:
// as a class method:
class example
{
...
public:
...
example operator + (int right) const;
};
example example::operator + (int right) const
{
example temp;
temp.seta(a + right);
return temp;
}或者:
// as a global operator:
class example
{
...
public:
...
friend example operator + (const example& left, int right);
};
example operator + (const example& left, int right)
{
example temp;
temp.seta(left.a + right);
return temp;
}如果您已经定义了一个以int作为输入的构造器,那么当您将int值传递给example::operator+(const example&)方法时,编译器可能已经创建了一个临时int,例如:
class example
{
...
public:
example (int f);
...
example operator + (const example& right);
};
example::example::(int f)
: a(f)
{
}
example example::operator + (const example& right)
{
example temp;
temp.a = a + right.a;
return temp;
}同样,t = 1 + r;的意思是t = operator+(1, r); (因为1不是类类型)。它没有编译,因为您没有定义一个全局+操作符,该操作符在左边接受一个int,在右边定义一个example:
class example
{
...
public:
...
friend example operator + (int left, const example& right);
};
example operator + (int left, const example& right)
{
example temp;
temp.a = left + right.a;
return temp;
}https://stackoverflow.com/questions/22209434
复制相似问题