设为首页 加入收藏

TOP

C++ const函数返回值必须为const引用
2014-11-24 07:20:52 来源: 作者: 【 】 浏览:1
Tags:const 函数 返回 必须 引用

编译正确代码:


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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇二叉查找树C语言实现 下一篇C++类static静态成员变量和const..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·数据库:推荐几款 Re (2025-12-25 12:17:11)
·如何最简单、通俗地 (2025-12-25 12:17:09)
·什么是Redis?为什么 (2025-12-25 12:17:06)
·对于一个想入坑Linux (2025-12-25 11:49:07)
·Linux 怎么读? (2025-12-25 11:49:04)