必须以成员函数形式重载
#include <iostream>
using namespace std;
class CGirl {
private:
string m_boys[3];
public:
string m_name;
CGirl() {
m_boys[0] = "zhongge";
m_boys[1] = "ouge";
m_boys[2] = "zhuge";
}
void show() {
cout << m_boys[0] << m_boys[1] << m_boys[2] << endl;
}
const string &operator[](int i) const {
return m_boys[i];
}
};
int main() {
CGirl g;
g.show();
cout << g[1] << endl;
const CGirl g1 = g;
cout << g1[2];
return 0;
}
重载运算符前后都加上const更普适;