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/