#include <iostream>
#include <cstring>
class CTextBlock
{
public:
CTextBlock(char* tmp)
{
pText = tmp;
}
char& operator[](std::size_t position) const
{
std::cout << "const function" << std::endl;
return pText[position];
}
private:
char* pText;
};
int main()
{
const CTextBlock cctb("Hello");
char* pc = &cctb[0];
*pc = 'J';
return 0;
}
这个问题怎么解决哦?
我尝试注释掉构造函数中的那一条语句,并把传入参数修改为const类型,编译是可以通过,但是我想的是传入这个字符串并把它赋值给另一个变量,这该怎么解决啊。
If you just don’t see this warning, you can add -Wno-write-strings when compiling.
If you want to organize the code in a reasonable way to avoid warnings, you can use:
My personal suggestion is to use string.
"Hello"
This is a string literal. It is placed in the constant area of the program (the compiler may optimize it away), so passing the address to achar*
will naturally cause a warningEither replace it with
const char*
or useconst_cast
.I also recommend using
std::string
personally.