问题
I want to implement "operator * " overloading INSIDE my class, so I would be able to do the following:
Rational a(1, 2), b;
b = 0.5 * a; // b = 1/4
Notice that b is on the right side, is there a way to do such a thing inside "Rational" class?
回答1:
No. You must define operator*
as a free function. Of course, you could implement it in terms of a member function on the second argument.
回答2:
Yes:
class Rational {
// ...
friend Rational operator*(float lhs, Rational rhs) { rhs *= lhs; return rhs; }
};
Note: this is of course an abuse of the friend
keyword. It should be a free function.
回答3:
Answer is no you cannot, but since float value is on left side you may expect that type of result from "0.5 * a" will be double. In that case you may consider doing something about conversion operator. Please note that "pow(a, b)" is added only to illustrate the idea.
1 #include <stdio.h>
2 #include <math.h>
3
4 class Complicated
5 {
6 public:
7 Complicated(int a, int b) : m_a(a), m_b(b)
8 {
9 }
10
11 Complicated(double a) : m_a(a)
12 {
13 }
14
15 template <typename T> operator T()
16 {
17 return (T)(pow(10, m_b) * m_a);
18 }
19
20 void Print()
21 {
22 printf("(%f, %f)\n", m_a, m_b);
23 }
24
25 private:
26 double m_a;
27 double m_b;
28 };
29
30
31 int main(int argc, char* argv[])
32 {
33 Complicated pr(1, 2);
34 Complicated c = 5.1 * (double) pr;
35 c.Print();
36 }
37
来源:https://stackoverflow.com/questions/4846396/how-do-i-overload-the-operator-when-my-object-is-on-the-right-side-in-c