编译正确代码:
- #include<stdio.h>
- #include <string.h>
- #include<iostream>
- using namespace std;
- class T{
- public:
- T(string p)
- {
- ptext = p;
- }
- const char & operator [](int pos) const
- {
- return ptext[pos];
- }
- string ptext;
- };
- int main()
- {
- string s = "abcd";
- T t(s);
- //t[0] = 't';//因为为const返回类型,所以不能赋值
- printf("%s\n", s.c_str());
- }
编译错误代码:
- #include<stdio.h>
- #include <string.h>
- #include<iostream>
- using namespace std;
- class T{
- public:
- T(string p)
- {
- ptext = p;
- }
- char & operator [](int pos) const//返回类型不为const编译错误
- {
- return ptext[pos];
- }
- string ptext;
- };
- int main()
- {
- string s = "abcd";
- T t(s);
- //t[0] = 't';//因为为const返回类型,所以不能赋值
- printf("%s\n", s.c_str());
- }
本文探讨了C++中类成员操作符重载时返回类型的常量性问题,通过对比正确的编译代码与错误的编译代码,解释了为何在实现类成员[]操作符时需要将其声明为返回const引用,以防止对返回的对象进行修改。
1095

被折叠的 条评论
为什么被折叠?



