c++ operator 灵活用法 借助operator访问私有成员
来源:互联网 发布:java异常处理finally 编辑:程序博客网 时间:2024/06/05 02:31
头文件
#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;
}
- c++ operator 灵活用法 借助operator访问私有成员
- C++operator用法.
- operator 用法
- operator.c
- C++Operator
- operator->*
- operator[]
- operator
- operator
- operator.*()
- operator[]
- Operator
- operator
- operator
- operator ->
- operator
- operator ++
- .operator
- 给初学者的RxJava2.0教程(八)
- 练习
- 多线程练习题
- js和jquery小对比
- android 接口回调---java 接口回调(一看就会)
- c++ operator 灵活用法 借助operator访问私有成员
- Spring事务的传播行为和隔离级别
- java基础6
- TIME_WAIT 太多的解决办法[转载]
- Callable,Runnable比较及用法
- 2017-编程
- Java8新特性
- Java实现栈结构
- 错误2error LNK2005: *已经在 *.obj 中定义(使用多个.cpp文件时,应注意的事项)