C++ operator 知识点 2

时间:2022-06-01 20:08:52

http://blog.csdn.net/szlanny/article/details/4295854

operator它有两种用法,一种是operator overloading(操作符重载),一种是operator casting(操作隐式转换)。

1.operator overloading
C++可以通过operator 重载操作符,格式如下:类型T operator 操作符 (),如比重载+,如下所示

  1. template<typename T> class A
  2. {
  3. public:
  4. const T operator + (const T& rhs)
  5. {
  6. return this->m_ + rhs;
  7. }
  8. private:
  9. T m_;
  10. };

又比如STL中的函数对象,重载(),这是C++中较推荐的写法,功能与函数指针类似,如下所示

  1. template<typename T> struct A
  2. {
  3. T operator()(const T& lhs, const T& rhs){ return lhs-rhs;}
  4. };

2 operator casting
C++可以通过operator 重载隐式转换,格式如下: operator 类型T (),如下所示

  1. class A
  2. {
  3. public:
  4. operator B* () { return this->b_;}
  5. operator const B* () const {return this->b_;}
  6. operator B& () { return *this->b_;}
  7. operator const B& () const {return *this->b_;}
  8. private:
  9. B* b_;
  10. };

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;

}