• C++ operator 知识点 2


    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++中较推荐的写法,功能与函数指针类似,如下所示

    [c-sharp] view plaincopy
    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.   
    9. private:  
    10.    B* b_;  
    11. }; 

    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() ");

    return m_buf;
    }

    operator char*()
    {
    memset(m_buf, 0, 30);
    strcpy(m_buf, "char *");
    printf("char * ");

    return m_buf;
    }

    public:
    char m_buf[30];

    };


    int main()
    {
    Test a(5), b(15);

    a = b;
    printf("a.m_age=%d ", a.m_age);//15

    a += b;
    printf("a.m_age=%d ", a.m_age);//30

    TestB bb;
    char *ptest1 = bb; //printf char * 这里TestB 被转化为 char *
    char *ptest2 = bb.getStr(); //printf get str()

    return 0;

    }

  • 相关阅读:
    getchar,putchar函数
    强制类型转换和整数常量的数据类型及转换
    c语言整型的隐式数据 类型转换
    c语言整型数据输出格式声明
    c语言整型变量的储存空间,以及所表示的整数范围
    c语言常量
    c语言求回文数
    Android4.0源码目录结构详解
    MTK Android源代码目录
    Comparator 和 Comparable
  • 原文地址:https://www.cnblogs.com/maxpak/p/4487422.html
Copyright © 2020-2023  润新知