Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C++ 為什麼 const 成員函數的返回值要宣告為 const 引用

這對比一組程式碼就能看出差別。

可以編譯的版本

#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& 即可解決。

Copyright © Linux教程網 All Rights Reserved