Home  >  Q&A  >  body text

c++ - 字符串常量转换问题

#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类型,编译是可以通过,但是我想的是传入这个字符串并把它赋值给另一个变量,这该怎么解决啊。

伊谢尔伦伊谢尔伦2764 days ago575

reply all(3)I'll reply

  • 阿神

    阿神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.

    reply
    0
  • 怪我咯

    怪我咯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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:19:28

    Either replace it with const char* or use const_cast.

    I also recommend using std::string personally.

    reply
    0
  • Cancelreply