#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类型,编译是可以通过,但是我想的是传入这个字符串并把它赋值给另一个变量,这该怎么解决啊。
阿神2017-04-17 13:19:28
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:
char c[] = "Hello";
const CTextBlock cctb(c);
My personal suggestion is to use string.
怪我咯2017-04-17 13:19:28
"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 a char*
will naturally cause a warning
ringa_lee2017-04-17 13:19:28
Either replace it with const char*
or use const_cast
.
I also recommend using std::string
personally.