class Name
{
//重载的输出运算符,声明为类的友元函数
friend ostream& operator<<(ostream& o, const Name& other);
private:
string FirstName;
string MidName;
string LastName;
};
//输出运算符重载为全局函数
ostream& operator<<(ostream& o, const Name& other)
{
cout << other.FirstName << " " << other.MidName << " " << other.LastName;
return o;
}
main函数里的测试代码:
int main()
{
Name name;
name[0] = "FF";
name[1] = "MM";
name[2] = "LL";
cout << name;
return 0;
}
运行效果:
最终代码:class Name
{
//重载的输出运算符,声明为类的友元函数
friend ostream& operator<<(ostream& o, const Name& other);
public:
//重载的下标运算符
string& operator[](int index)
{
switch (index)
{
case 0:
return FirstName;
case 1:
return MidName;
case 2:
return LastName;
}
}
private:
string FirstName;
string MidName;
string LastName;
};


![C++重载下标运算符[ ] C++重载下标运算符[ ]](http://www.mshxw.com/aiimages/31/767943.png)
