【发布时间】:2011-05-02 22:45:34
【问题描述】:
int a, b, c;
//do stuff. For e.g., cin >> b >> c;
c = a + b; //works
c = operator+(a,b); //fails to compile, 'operator+' not defined.
另一方面,这有效 -
class Foo
{
int x;
public:
Foo(int x):x(x) {}
Foo friend operator+(const Foo& f, const Foo& g)
{
return Foo(f.x + g.x);
}
};
Foo l(5), m(10);
Foo n = operator+(l,m); //compiles ok!
- 甚至可以直接调用基本类型(如 int)的 operator+(和其他运算符)吗?
- 如果是,怎么做?
- 如果没有,是否有 C++ 参考措辞明确表明这是不可行的?
【问题讨论】:
-
我很好奇,你为什么要这样做?
-
我正在尝试帮助某人学习 C++,我说的是运算符的行为类似于函数的想法。我想展示一段名为 operator+(2,3) 而不是 2+3 的代码来说明这个想法,因为我意识到它并没有像我预期的那样工作。
标签: c++ function operator-keyword