歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++ const函數返回值必須為const引用

C++ const函數返回值必須為const引用

日期:2017/3/1 9:57:46   编辑:Linux編程

編譯正確代碼:

#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());
}

Copyright © Linux教程網 All Rights Reserved