我想寫一個字符串類。並希望使用下標訪問我的字符串中的元素。因此,我編寫了兩個成員函數,一個用於獲取字符串中的元素,另一個用於設置字符串中的元素。請看下面的代碼;如何在C++中重載訪問器和mutator運算符[]
#include <iostream>
#include <algorithm>
using namespace std;
class String {
public:
String();
String(const char *s);
char &operator[] (int index);
char operator[] (int index) const;
private:
char *arr;
int len;
};
String::String() {
arr = new char[1];
arr[0] = '\0';
len = 0;
}
String::String(const char *s) {
len = strlen(s);
arr = new char[len + 1];
std::copy(s, s + len + 1, arr);
}
//mutator operator[] ---> used to change data members;
char& String::operator[](int index)
{
cout << "mutator []" << endl;
if (index > len || index < 0)
throw std::out_of_range("Index out of range");
return arr[index];
}
//Accessor operator[]---> used to read data members
char String::operator[](int index) const
{
cout << "accessor []" << endl;
if (index > len || index < 0)
throw std::out_of_range("Index out of range");
return arr[index];
}
int main()
{
String s1 = "abc";
s1[1] = 'b'; //---> should use mutator operator
String s2 = "efg";
s2[1] = s1[2]; //---> should use both accessor and mutator operator
char a = s1[2]; //---> should use accessor operator
cout << s2[1] << endl; //---> should use accessor operator
}
當我運行此代碼。它的輸出全部是mutator
;它使我困惑不已;