我想重载运算符 ,
以便我可以使用以下语法分配分数:
frac = 1, 2
。它在没有 ()
运算符的情况下工作正常。
#include <iostream>
using namespace std;
class fraction {
private:
int m_num;
int m_den;
public:
fraction(int num, int den)
:m_num(num), m_den(den) {
}
fraction& operator =(int num) {
m_num = num;
return *this;
}
fraction& operator ,(int den) {
m_den = den;
return *this;
}
public:
friend
ostream& operator <<(ostream& out, const fraction& rhs) {
return out << rhs.m_num << ", " << rhs.m_den;
}
};
int main() {
fraction f(1, 2);
cout << "original f = " << f << endl;
f = 4, 5;
cout << "expected = " << f << endl;
f = (10, 11);
cout << "unexpected = " << f << endl;
}
**输出
$ prog.exe
original f = 1, 2
expected = 4, 5
unexpected = 11, 5
我不小心在num
和den
两边加了一个()
,从输出中我意识到了operator()的优先级
影响了实际结果。它仅使用 operator
进行评估,这很奇怪。所以我的问题是,在这种特殊情况下,有没有办法(也许是宏?)忽略运算符 ()
的影响?
最佳答案
只有当至少一个参数是用户定义的时,您才能重载运算符。在您的情况下,您的两个参数都是 int
,因此您无能为力。
(除了避免有问题地使用 operator,
!)
关于c++ - 有没有办法覆盖括号的默认行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9864667/