简体   繁体   English

C ++从左到右重载[]

[英]C++ Overloading [] from left and right

I'm trying to think how can I overload [] from both left and right to function as set and get for a custom string class I'm working on. 我正在考虑如何从左侧和右侧重载[]以设置为函数并获取我正在处理的自定义字符串类。 for example: 例如:

char x= objAr[1]; //get
objAr[2]='a'; //set

The string class basically looks like this: 字符串类基本上如下所示:

class String {
private:
    char* data;
    unsigned int dataSize;
public:
    String();
    String(char);
    String(char*);
    String(String&);
    ~String();
    char* getData();
    int getSize();
};

If you always have the data to back it up, you can return a reference: 如果您始终拥有备份数据,则可以返回参考:

char& String::operator[] (size_t idx)
{ return data[idx]; }

char String::operator[] (size_t idx) const
{ return data[idx]; }

In your case, that should be sufficient. 在你的情况下,这应该是足够的。 However, if this was not option for whatever reason (eg if the data is not always of the proper type), you could also return a proxy object: 但是,如果由于某种原因这不是选项(例如,如果数据不总是正确类型),您还可以返回代理对象:

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

This would also enable you to do things like implicit data sharing with copy-on-write. 这还可以让您通过写时复制执行隐式数据共享等操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM