http://blog.csdn.net/szlanny/article/details/4295854
Operator it has two usages, one is operator overloading (operator overloading), and the other is operator casting (operation implicit conversion).
1.operator overloading
C + + can be overloaded with operator operators, in the following format: type T operator operator (), such as gravity Load +, as shown below
[CPP]View Plaincopy
- template<TypeName t> class A
- {
- Public
- Const T operator + (const t& RHS)
- {
- return this->m_ + RHS;
- }
- Private
- T m_;
- };
Another example is the function object in STL, overloaded (), which is the more recommended notation in C + +, similar to function pointers, as shown below
[C-sharp]View Plaincopy
- Template<typename t> struct A
- {
- T operator () (const t& LHS, const t& RHS) { return LHS-RHS;}
- };
2 operator Casting
C + + can be operator overloaded with implicit conversions in the following format: operator type T (), as shown below
[CPP]View Plaincopy
- Class A
- {
- Public
- Operator b* () { return this->b_;}
- operator Const b* () const {return this->b_;}
- Operator b& () { return *this->b_;}
- operator Const b& () const {return *this->b_;}
- Private
- b* b_;
- };
A;
When the if (a), compile, where it is converted to if (A.operator b* ()), in fact is to judge if (A.b_)
I have a close-up of 2 examples of these two usages.
Class Test//Overloaded classes
{
Public
Test (int a)
{
M_age = A;
}
~test () {}
Test operator = (test &temp)
{
This->m_age = Temp.m_age;
return *this;
}
Test operator + = (Test & TEMP2)
{
This->m_age + = Temp2.m_age;
return *this;
}
Public
int m_age;
};
Class TESTB//Implicit conversion
{
Public
Testb () {}
~testb () {}
char* Getstr ()
{
memset (m_buf, 0, 30);
strcpy (M_BUF, "Get Str ()");
printf ("Get str () \ n");
return m_buf;
}
Operator char* ()
{
memset (m_buf, 0, 30);
strcpy (M_BUF, "char *");
printf ("Char *\n");
return m_buf;
}
Public
Char m_buf[30];
};
int main ()
{
Test A (5), B (15);
A = b;
printf ("a.m_age=%d\n", a.m_age);//15
A + = B;
printf ("a.m_age=%d\n", a.m_age);//30
TESTB BB;
char *ptest1 = BB; printf char * Here TESTB is converted to char *
Char *ptest2 = BB.GETSTR (); printf Get str ()
return 0;
}
C + + operator Knowledge Point 2