operator[],识别读操作和写操作

operator[],识别读操作和写操作

转载自 https://www.cnblogs.com/meihao1203/p/8949516.html

root@iZ2zee0spkwcgvz4do5kt2Z:~/docker_use/cpp_study/string_prj# cat string_operator.cpp
#include
#include
using namespace std;
class String
{ //23种设计模式之代理模式
        class charProxy;
        public:
                String():_pstr(new char[2])
                {
                        cout<<"String()"<>(istream&,String&);
};
#if 0
//operator[]()不能区分读操作还是写操作
char & String::operator[](int idx)const       //不能区分读写操作,废弃
{
        cout<<"operator [](int)const"<>(istream& is,String& s)
{
        cout<<"istream& operator>>(istream&,String&)"<>s._pstr;
        return is;
}
String::charProxy String::operator[](int index)
{
        cout<<"charProxy operator[](int)"<=0&&_index

run 一下

root@iZ2zee0spkwcgvz4do5kt2Z:~/docker_use/cpp_study/string_prj# ./string_operator
String(const char*)
String(const String&)
charProxy operator[](int)
charProxy(String&,int)
operator char()
读操作:e
2
--------------------------
写操作:
charProxy operator[](int)
charProxy(String&,int)
char& operator=(char)
String(const char*)
String& operator=(const String&)
~String()
charProxy operator[](int)
charProxy(String&,int)
char& operator=(char)
--------------------------
charProxy operator[](int)
charProxy(String&,int)
operator char()
m
1
~String()
~String()

你可能感兴趣的:(operator[],识别读操作和写操作)