I want to implement "operator * " overloading INSIDE my class, so I would be able to do the follo开发者_运维知识库wing:
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?
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.
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.
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
精彩评论