Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+;中实现C-API文本块类时出错+; 类文本 { 公众: 字符和运算符[](内部位置)常量 {返回文本[pos];} char*get()常量 {返回文本;} 私人: char*text=“你好”; }; int main() { 案文a; char*x=&a[0]; *x='s'; cout_C++_C_Char - Fatal编程技术网

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;
}