c++ - 在C++中实现C-API文本 block 类时出错

标签 c++ c char

class Text
{
public :   
       char& operator[](int pos) const   
       {return text[pos];}

        char* get() const
       {return text;}
private: 
     char* text = "hello";
};
int main() 
{
     Text a;
    char * x = &a[0];
    *x = 's';
    
    cout << a.get() << endl;

}
我正在阅读Scott Meyers高效的C++书,有一个我必须自己实现的类,所以我尝试自己实现,但是该程序一直崩溃。

最佳答案

这行:

char* text = "hello";
无效的C++,因为字符串文字会衰减为 const char *。使用正确的命令行标志,您的编译器应已对此发出警告。
从那里继续,*x = 's';导致未定义的行为,因为x指向所述字符串文字。实际上,您会遇到段错误,因为您试图写入只读内存。

编辑:这是使用std::string的固定版本:
#include <string>

class Text
{
public :   
     char& operator[](int pos) {return text[pos];}
     const char* get() const {return text.c_str ();}
private: 
     std::string text = "hello";
};

int main() 
{
    Text a;
    char * x = &a[0];
    *x = 's';
    
    std::cout << a.get() << std::endl;
}
Live demo

关于c++ - 在C++中实现C-API文本 block 类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63876782/

相关文章:

matlab 字符数组到元胞数组

c++ - C++中的结构和函数

c++ - 为什么 C++ 中的多重定义错误不是由 const int 声明引起的?

c - 从不兼容的指针类型赋值——如何解决?

c - 如何在 Visual Studio 中修复 "return value ignored: ' scanf'"代码 C6031

c++ - 如何将字符串 vector 传递给 foo(char const *const *const)?

c++ - netbeans c++ googletest 从 gui 运行测试

c++ - CRTP 层次类的非模板基类

c - execv vs execvp,为什么其中一个需要确切的文件路径?

Java 字符 [] 到字符串