c++ operator 灵活用法 借助operator访问私有成员

头文件

#ifndef __header__
#define __header__
#include<string>
using namespace std;

class TEST
{
        public:
        string test;
        TEST(char *buf);
        TEST();
        ~TEST();
        char data[20];
        char * operator()();   //返回私有成员字符串
};

#endif


实现文件

#include"head.hpp"
#include <string.h>
#include <iostream>


using namespace std;

TEST::TEST()
{
        cout<<"constructor() "<<endl;
}

TEST::TEST(char*buf)
{
        cout<<"constructor() "<<endl;
        memset(data,0x00,sizeof(data));
        memcpy(data,buf,sizeof(data));
}

TEST::~TEST()
{
        cout<<"destroy constrcut() "<<endl;
}

char *TEST::operator()()
{
        return data;
}

测试文件

#include"head.hpp"
#include<string>
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{
                char buf[8]={0x00};
                memcpy(buf,"hello",6);

                TEST tt(buf);
                char *buf1 =    tt();

                cout<<"buf=="<<tt.data<<endl;
                cout<<"buf1=="<<buf1<<endl;

                return 0;
}




头文件

#ifndef __header__
#define __header__
#include<string>
using namespace std;

struct test_struct
{
         int i;
};

class TEST
{
    private:
    struct test_struct *tt;
    public:
    TEST();
    TEST(int a);
    ~TEST();
    operator struct test_struct*(); //返回私有成员结构体指针
};

#endif

实现文件

#include"head.hpp"
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>

using namespace std;

TEST::TEST()
{
    cout<<"constructor() "<<endl;
}

TEST::TEST(int a)
{
    cout<<"test struct constructor"<<endl;
    tt = (struct test_struct*)malloc(sizeof(struct test_struct));
    tt->i = a;
}

TEST::~TEST()
{
    cout<<"destroy constrcut() "<<endl;
}

TEST::operator struct test_struct*()
{
    return tt;
}

测试文件

#include"head.hpp"
#include<string>
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

int main()
{

        TEST t(5);
        struct test_struct *a;
        //a=*t; //wrong
        a=t;    
        cout<<"a->i="<<a->i<<endl;
        //cout<<"t->i"<<t->i<<endl; //wrong
        //cout<<"t.tt->i"<<t.tt.->i<<endl; //wrong
        
        return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值