C++从左向右重载[]
C++ Overloading [] from left and right
我正在考虑如何从左侧和右侧重载 [] 以作为 set 运行并获取我正在处理的自定义字符串 class。例如:
char x= objAr[1]; //get
objAr[2]='a'; //set
字符串class基本上是这样的:
class String {
private:
char* data;
unsigned int dataSize;
public:
String();
String(char);
String(char*);
String(String&);
~String();
char* getData();
int getSize();
};
如果你一直有数据备份,可以return参考一下:
char& String::operator[] (size_t idx)
{ return data[idx]; }
char String::operator[] (size_t idx) const
{ return data[idx]; }
在你的情况下,这应该足够了。但是,如果出于某种原因这不是选项(例如,如果数据不总是正确的类型),您还可以 return 一个代理对象:
class String
{
void setChar(size_t idx, char c);
char getChar(size_t idx);
class CharProxy
{
size_t idx;
String *str;
public:
operator char() const { return str->getChar(idx); }
void operator= (char c) { str->setChar(idx, c); }
};
public:
CharProxy operator[] (size_t idx)
{ return CharProxy{idx, this}; }
const CharProxy operator[] (size_t idx) const
{ return CharProxy{idx, this}; }
};
这还可以让您使用写时复制进行隐式数据共享等操作。
我正在考虑如何从左侧和右侧重载 [] 以作为 set 运行并获取我正在处理的自定义字符串 class。例如:
char x= objAr[1]; //get
objAr[2]='a'; //set
字符串class基本上是这样的:
class String {
private:
char* data;
unsigned int dataSize;
public:
String();
String(char);
String(char*);
String(String&);
~String();
char* getData();
int getSize();
};
如果你一直有数据备份,可以return参考一下:
char& String::operator[] (size_t idx)
{ return data[idx]; }
char String::operator[] (size_t idx) const
{ return data[idx]; }
在你的情况下,这应该足够了。但是,如果出于某种原因这不是选项(例如,如果数据不总是正确的类型),您还可以 return 一个代理对象:
class String
{
void setChar(size_t idx, char c);
char getChar(size_t idx);
class CharProxy
{
size_t idx;
String *str;
public:
operator char() const { return str->getChar(idx); }
void operator= (char c) { str->setChar(idx, c); }
};
public:
CharProxy operator[] (size_t idx)
{ return CharProxy{idx, this}; }
const CharProxy operator[] (size_t idx) const
{ return CharProxy{idx, this}; }
};
这还可以让您使用写时复制进行隐式数据共享等操作。