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

 

 

原文链接: https://www.cnblogs.com/javawebsoa/archive/2013/04/30/3052278.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

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

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/86562

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午10:38
下一篇 2023年2月9日 下午10:39

相关推荐