C++ 在C+;中实现C-API文本块类时出错+; 类文本 { 公众: 字符和运算符[](内部位置)常量 {返回文本[pos];} char*get()常量 {返回文本;} 私人: char*text=“你好”; }; int main() { 案文a; char*x=&a[0]; *x='s'; cout
这条线:C++ 在C+;中实现C-API文本块类时出错+; 类文本 { 公众: 字符和运算符[](内部位置)常量 {返回文本[pos];} char*get()常量 {返回文本;} 私人: char*text=“你好”; }; int main() { 案文a; char*x=&a[0]; *x='s'; cout,c++,c,char,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
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;
}
不有效C++,因为字符串文字衰减为<强> const char *。使用正确的命令行标志,编译器应该警告过您。 从这里开始,
*x='s';
导致未定义的行为,因为x
指向所述字符串文本。实际上,您会遇到seg错误,因为您试图写入只读内存
编辑:这里有一个使用
std::string
的固定版本:
char* text = "hello";
#包括
课文
{
公众:
字符和运算符[](int-pos){返回文本[pos];}
const char*get()const{return text.c_str();}
私人:
std::string text=“hello”;
};
int main()
{
案文a;
char*x=&a[0];
*x='s';
std::cout这可能会帮助您了解文字字符串实际上是常量字符的数组。试图修改文字字符串会导致未定义的行为。@Berto99终于!谢谢,这帮助我澄清了我的疑问。哦,我明白了,谢谢,有什么方法可以修复它吗?因为在这本书中给出了这样一种方式,您可能可以用它来制作一些东西。@Xcalibe这本书是否真的使用了指针或数组(如chartext[]=“hello”
)?@Someprogrammerdude OP说他必须自己实现这个类。
#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;
}