运行无法达到效果
#include
#include
using namespace std;
class mystring{
private:
char *p;
public:
mystring(char *a){
p = a;
}
void set(char b){
p[0] = b;
}
void show(){
cout << *p << endl;
}
~mystring(){
delete[]p;
cout << "free memory!" <int main() {
mystring s1("hello");
mystring s2 = s1;
s1.set('H'); // 修改字符串的第一个字符
s1.show();
s2.show();
return 0;
}
报错内容为[Warning] ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
想要的效果为
Hello
hello
free memory!
free memory!
努力の小熊参考Chatgpt做出的回答:
代码中出现错误的原因是:将字符串常量直接赋值给了 char* 指针类型变量,但是字符串常量在 C++ 中是不可修改的,将其赋值给 char* 指针类型变量会导致编译器报错。正确的做法应该是使用 const char* 类型来保存字符串常量。
另外,代码中没有实现拷贝构造函数和赋值运算符重载函数,当 s1 赋值给 s2 时,s2 也指向了 s1 的数组,这样会导致析构函数释放内存时出现错误。
下面是改正后的代码:
#include <iostream>
#include <cstring> // 需要包含这个头文件以使用 strcpy 函数
using namespace std;
class mystring{
private:
char *p;
public:
mystring(const char *a){
p = new char[strlen(a) + 1];
strcpy(p, a);
}
mystring(const mystring& other){
p = new char[strlen(other.p) + 1];
strcpy(p, other.p);
}
void set(char b){
p[0] = b;
}
void show(){
cout << p << endl;
}
~mystring(){
delete[]p;
cout << "free memory!" <<endl;
}
mystring& operator=(const mystring& other){
if (this != &other) {
delete[] p;
p = new char[strlen(other.p) + 1];
strcpy(p, other.p);
}
return *this;
}
};
int main() {
mystring s1("hello");
mystring s2 = s1;
s1.set('H'); // 修改字符串的第一个字符
s1.show();
s2.show();
return 0;
}
在改正后的代码中,使用 const char* 类型来保存字符串常量并使用 strcpy 函数复制到新分配的内存空间中;实现了拷贝构造函数和赋值运算符重载函数,避免了出现错误。
该回答通过自己思路及引用到GPTᴼᴾᴱᴺᴬᴵ搜索,得到内容具体如下:
这个程序的问题在于,构造函数 mystring(char *a)
接受的是一个 char*
类型的指针,然而在主函数中使用了字符串常量 "hello"
来初始化对象 s1
,这会导致编译器给出警告,提示字符串常量不应该被用于初始化 char*
类型的指针。
为了解决这个问题,您可以将构造函数的参数类型改为 const char*
,并使用 new
运算符动态分配内存来存储字符串。同时,在拷贝构造函数中也需要进行类似的修改,以避免使用被释放的内存。
以下是修改后的代码:
#include <iostream>
#include <string>
using namespace std;
class mystring{
private:
char *p;
public:
mystring(const char *a){
p = new char[strlen(a) + 1];
strcpy(p, a);
}
mystring(const mystring& s){
p = new char[strlen(s.p) + 1];
strcpy(p, s.p);
}
void set(char b){
p[0] = b;
}
void show(){
cout << p << endl;
}
~mystring(){
delete[]p;
cout << "free memory!" << endl;
}
};
int main() {
mystring s1("hello");
mystring s2 = s1;
s1.set('H'); // 修改字符串的第一个字符
s1.show();
s2.show();
return 0;
}
在这个修改后的程序中,我们将构造函数的参数类型修改为 const char*
,并使用 new
运算符动态分配内存来存储字符串。在拷贝构造函数中也进行了类似的修改。最后,我们使用 cout
函数输出字符串的内容。
希望这个修改后的程序能够帮到您!
如果以上回答对您有所帮助,点击一下采纳该答案~谢谢
比如代码:
int bs_reserve(int fd, BSJ **result) {
return bs_reserve_job(fd, "reserve\r\n", result);
}
int bs_reserve_job(int fd, char *command, BSJ **result);
修正方法:
int bs_reserve(int fd, BSJ **result) {
char command[] = "reserve\r\n";
return bs_reserve_job(fd, command, result);
}