C++ operator 知识点 2
http://blog.csdn.net/szlanny/article/details/4295854
operator它有两种用法,一种是operator overloading(操作符重载),一种是operator casting(操作隐式转换)。
1.operator overloading
C++可以通过operator 重载操作符,格式如下:类型T operator 操作符 (),如比重载+,如下所示
- template<typename T> class A
- {
- public:
- const T operator + (const T& rhs)
- {
- return this->m_ + rhs;
- }
- private:
- T m_;
- };
又比如STL中的函数对象,重载(),这是C++中较推荐的写法,功能与函数指针类似,如下所示
- template<typename T> struct A
- {
- T operator()(const T& lhs, const T& rhs){ return lhs-rhs;}
- };
2 operator casting
C++可以通过operator 重载隐式转换,格式如下: operator 类型T (),如下所示
- 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 a;
当if(a),编译时,其中它转换成if(a.operator B*()),其实也就是判断 if(a.b_)
正对这两个用法,自己特写了2个例子。
class Test //重载的类
{
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 //隐式转换
{
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 * 这里TestB 被转化为 char *
char *ptest2 = bb.getStr(); //printf get str()
return 0;
}