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());
}
[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());
}
相关文章推荐
- leetcode_c++:栈:Flatten Nested List Iterator(341)
- C++ Primer 笔记(2)第二章 变量与基本类型
- leetcode_c++:栈: Verify Preorder Serialization of a Binary Tree(331 )
- 1092. To Buy or Not to Buy (20)
- leetcode_c++:栈:Remove Duplicate Letters(316 )
- vector::clear ,vector::crbegin (c++11),vector::crend(c++11)
- vector::cend (c++ 11)
- vector::cbegin (c++11)
- 大话设计模式12----外观模式
- C++ vector用法
- 并查集C++实现
- leetcode_c++:栈: Implement Queue using Stacks(232)
- c++ 在windwos上创建盘符,并且,监控盘符里面任一文件的变动事件
- 谈谈8年C++面向对象设计的经验体会
- C/C++头文件大全
- leetcode_c++:栈: Implement Stack using Queues(225)
- 模拟实现strstr函数
- Google C++编程规范--《空格的使用》
- leetcode_c++:栈: Basic Calculator(224)
- C++小常识笔记