了解 char 和 const
Understanding char & and const
我正在学习c++,在理解一些概念方面有困难。在下面的程序中,(1)为什么使用char&
而不是char
,我认为它应该只使用char
,因为成员函数返回text[position]
,这是char
类型,而不是引用。(2)在const char& operator[](std::size_t position) const
中,为什么第二个const
是必要的?我试图删除它,只保留第一个const
,但它报告了错误。谢谢你!
#include<iostream>
#include<string>
class TextBook{
public:
TextBook(std::string s)
{
text.assign(s);
}
const char& operator[](std::size_t position) const {
return text[position];
}
char& operator[](std::size_t position){
return text[position];
}
private:
std::string text;
};
int main()
{
const TextBook ctb("Hello");
std::cout << ctb[0] << std::endl;
TextBook tb("Morning");
tb[2]='M';
std::cout << tb[2] << std::endl;
}
编辑:当我提到"first"answers"second"时,我分别指的是非const和const版本。
在第一种情况下,如果调用者希望修改字符串,则必须返回一个引用。通过返回对字符串中某个字符的引用,可以这样调用:
book[index] = 'a';
实际上会修改底层字符串本身,因为操作符将返回对字符串中实际字符的引用,而不是索引处字符的副本。
在第二个例子中,我们需要做两件事。我们正在创建另一个用于const对象的操作符[]。这个算子是不同的。正如您所注意到的,在方法声明之后有一个const。这意味着当在const对象上使用操作符[]时,将调用该操作符而不是非const版本。
const版本返回const引用,如果book
是const,则不可能编写这样的代码:
book[index] = 'a';
如果book
是const,这将调用第二个operator[]
并返回一个const引用。由于不能更改const引用,因此我们通过使用operator[]
1)函数的作用是返回对一个字符的引用。如果它只是返回值,main
中的代码将不起作用,因为它只会更改返回值。
2)这两个函数的重点是允许tb[2]
对const或非const TextBook
进行操作。对于非const对象,它返回一个非const引用。对于const对象,它返回一个const引用。