重载算术运算符 [英] Overloading Arithmetic Operators
问题描述
赋值运算符可以声明为
T& operator =(const t&);
T& operator= (const t&);
,但算术运算符不能这样定义。它必须是朋友的功能。我不明白为什么?
in a class, but the arithmetic operators cannot be defined that way. It has to be friend function. I don't understand why? Can you please explain ?
推荐答案
算术运算符不应该是朋友
It is not mandatory that arithmetic operators should be friend
你可以这样定义:
MyClass MyClass::operator + (const MyClass& t) const
{
MyClass ret(*this);
ret += t;
return ret;
}
a + b
真的是语法糖,编译器会将其扩展为 a.operator +(b)
。如果所有对象都是MyClass实例,上一个示例将会工作,但是如果你必须使用其他类型的对象,即 1 + a
The a + b
is really a syntax sugar, the compiler will expand it to a.operator+(b)
. The previous sample will work if all your objects are MyClass instances, but will not work if you have to operate with others types, ie 1 + a
, will not work, this can be solved by using friends.
MyClass operator + (int i, const MyClass& t)
{
MyClass ret(i);
ret += t;
return ret;
}
这必须在+操作符的左边不是一个类,或者它是一个类,但是你不能将operator +添加到它的定义。
This has to be done when the left hand side of the + operator is not a class, or it is a class but you can't add operator + to its definition.
这篇关于重载算术运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!