重载索引运算符赋值

问题描述 投票:0回答:1

我想重载为 C++ 类中的重载索引赋值。到目前为止,这是我的代码:

#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Test {
public:
    void operator=(vector<string> val) {
        a = val[0];
        b = val[1];
        c = val[2];
    }
    string operator[](int index) {
        if (index == 0) {
            return a;
        }
        else if (index == 1) {
            return b;
        }
        else {
            return c;
        }
    }
private:
    string a = "";
    string b = "";
    string c = "";
};
int main()
{
    // What I can do
    Test values;
    values = { "X","Y","Z" };
    cout << values[0] << endl;
    cout << values[2] << endl;
    //What I want to do:
    // values[1] = "XYZ";
}

我希望能够分配,而不仅仅是获取索引的值。 我怎么能这样做呢?例如

values[1] = "XYZ"
c++
1个回答
0
投票

要在 Test 类中启用对索引的分配,您可以重载下标运算符 [] 以返回对指定索引处的字符串的引用。然后,您可以直接修改该字符串。 检查一下:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

class Test {
 public:
    void operator=(const vector<string>& val) {
        if (val.size() >= 3) {
            a = val[0];
            b = val[1];
            c = val[2];
        }
    }

    string& operator[](int index) {
        if (index == 0) {
            return a;
        }
        else if (index == 1) {
            return b;
        }
        else {
            return c;
        }
    }

private:
    string a = "";
    string b = "";
    string c = "";
};

int main()
{
  Test values;
  values = { "X","Y","Z" };

  cout << values[0] << endl; // Output: X
  cout << values[2] << endl; // Output: Z

  values[1] = "XYZ"; // Assigning value to index 1
  cout << values[1] << endl; // Output: XYZ

  return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.