您的位置:首页 > 编程语言 > C语言/C++

C++ const函数返回值必须为const引用

2016-07-23 16:08 369 查看
编译正确代码:

[html] view
plain copy

 print?

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

}  

编译错误代码:

[html] view
plain copy

 print?

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

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: