operator的另一种用法:操作符隐式转换

看个例子:

#include "stdafx.h"

#include <iostream>

using namespace std;

 

class CTest

{

public:

    CTest(char * pMsg)

    {

        m_pMsg = new char[strlen(pMsg)+1];

        memset(m_pMsg, 0, strlen(pMsg)+1);

        memcpy(m_pMsg, pMsg, strlen(pMsg));

    }

 

    operator char * ()//把该类型隐式转换为char *

    {

        return m_pMsg;

    }

 

    ~CTest()

    {

        if (m_pMsg != NULL)

        {

            delete [] m_pMsg;

            m_pMsg = NULL;

        }

    }

 

private:

    char * m_pMsg;

};

 

bool intCom(int nData)

{

    return (nData > 5);

}

 

int _tmain()

{

    CTest test("what a fucking day");

 

    char * pMsg = test; // 注意这句

   

    system("pause");

    return 0;

}

重点分析CTest中的operator char * ()。重载了内置类型char *,该函数为什么没有返回值?因为返回值就是char *,和要重载的类型一样,故省略,这里所重载也许不正确。如果把Ctestoperator char * ()定义去掉,该程序无法编译。

如果不能理解,就请先死记它,随着知识的增长,总会明白的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值