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

    xiaoxiao2021-04-19  159

    头文件

    #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; }

    转载请注明原文地址: https://ju.6miu.com/read-676121.html

    最新回复(0)