這對比一組程式碼就能看出差別。
#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';
printf("%s\n", s.c_str());
}
原因在於:成員函數尾端的 const 承諾「不修改物件狀態」,但回傳 char& 卻等於把內部資料的可寫參照交出去,使用者就能藉此改動 ptext,與 const 承諾矛盾,因此編譯器直接拒絕。把回傳型別改成 const char& 即可解決。