zoukankan      html  css  js  c++  java
  • 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';//因为为const返回类型,所以不能赋值
    	printf("%s\n", s.c_str());
    }


  • 相关阅读:
    R语言-基本图形
    R语言-基本数据管理
    R语言—图像初阶
    R语言-实用数据对象处理函数
    R语言-数据结构
    scipy 的K-means
    python 解析命令行
    读取视频
    skimage
    face_recognition
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3052278.html
Copyright © 2011-2022 走看看