C++ operator关键字详解

C++中的operator主要有两个作用,一是操作符的重载,一是自定义对象类型的隐式转换。
类型转换操作符(type conversion operator)是一种特殊的类成员函数,它定义将类类型值转变为其他类型值的转换。
转换操作符在类定义体内声明,在保留字 operator 之后跟着转换的目标类型。

函数原型 
T1::operator T2() [const];   //T1的成员函数,"(T2)a"类型转换
说明:
1. 转换函数必须是成员函数,不能指定返回类型,并且形参表必须为空;返回值是隐含的,返回值是与转换的类型相同的,即为上面原型中的T2;

2. T2表示内置类型名(built-in type)、类类型名(class type)或由类型别名(typedef)定义的名字;
对任何可作为函数返回类型的类型(除了 void 之外)都可以定义转换函数,一般而言,不允许转换为数组或函数类型,
转换为指针类型(数据和函数指针)以及引用类型是可以的;

3. 转换函数一般不应该改变被转换的对象,因此转换操作符通常应定义为 const 成员;

4. 支持继承,可以为虚函数;

5. 只要存在转换,编译器将在可以使用内置转换的地方自动调用它;
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>    /* linux环境下,sprintf需要该头文件 */

using namespace std;

struct STData
{
    int data;
    int size;
};

class CTet
{
public:
    CTet(int age, string name,int data) :_age(age), _name(name) 
    {
        _data.data = data;
        _data.size = 10;
    }
public:
    operator char *() const;

    operator int() const
    {
        return _age;
    }

    operator struct STData() const
    {
        return _data;
    }

    operator const struct STData *() const
    {
        return &_data;
    }
private:
    int _age;
    string _name;
    STData _data;
};

//operator的隐式类型转化
CTet::operator char *() const
{
    //注意①:转化为指针的时候需要注意内存泄漏问题
    static char buf[100] = { 0 };
    sprintf(buf, "age[%d]:name[%s]", _age, _name.c_str());
    printf("buf = %p\n", buf);
    return buf;
}

void show_data(const STData *data)
{
    printf("data[%d] and size[%d] .\n", data->data, data->size);
}

void test()
{
    CTet a(10,"tom",22);
    /*
    可以直接将tmp对象转换成char *,这里实际上是编译器内部完成了以下转化
    char *b = a.operator char *();
    */
    char *b = a;
    //b的地址就是static char buf的地址
    printf("b = %p\n", b);

    /*
    注意②:operator的隐式类型转化的对象不能赋值给可变参数
    printf原型:int printf(const char *format, ...);
    */
    //printf("data is %s\n", a);  --无法编译通过

    printf("[b] data is %s\n", b); 

    CTet *tmp = new CTet(3, "jack", 5);
    //show_data(tmp);   --报错:无法将参数 1 从“CTet *”转换为“const STData *”

    /*
    注意③:operator的隐式类型转化只能用于栈变量,不可用于new出来的指针类型
    */

}

int main()
{
    test();
    getchar();
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhanggaofeng/p/9938358.html