c++ - 字符串常量转换问题
伊谢尔伦
伊谢尔伦 2017-04-17 13:17:28
0
3
574
#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类型,编译是可以通过,但是我想的是传入这个字符串并把它赋值给另一个变量,这该怎么解决啊。

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(3)
阿神

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.

刘奇

"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

左手右手慢动作

Either replace it with const char* or use const_cast.

I also recommend using std::string personally.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!