gpt4 book ai didi

c++ - 错误 : ISO C++ forbids converting a string constant to ‘char*’

转载 作者:行者123 更新时间:2023-12-05 03:25:24 24 4
gpt4 key购买 nike

<分区>

我正在尝试运行以下代码,摘自 Balagurusamy 的“C++ 面向对象编程”(第 8 版):

#include <iostream>
#include <cstring>
using namespace std;

class String
{
char *name;
int length;

public:

String()
{
length = 0;
name = new char[length+1];
}

String(char *s)
{
length = strlen(s);
name = new char[length+1];
strcpy(name,s);
}

void display(void)
{cout<<name<<"\n";}
void join(String &a, String &b);

};

void String :: join(String &a, String &b)
{
length = a.length + b.length;
delete name;
name = new char[length+1];

strcpy(name, a.name);
strcat(name, b.name);
};


int main()
{

char *first = "Joseph ";

String name1(first), name2("Louis"), name3("Lagrange"), s1,s2;

s1.join(name1, name2);
s2.join(s1,name3);

name1.display();
name2.display();
name3.display();

s1.display();
s2.display();

return 0;
}

当我用 g++ 编译时,我遇到了以下日志:

g++ -Wall -Werror -Wextra constructors_with_new.cpp -o constructors_with_new.o
constructors_with_new.cpp: In function ‘int main()’:
constructors_with_new.cpp:45:15: error: ISO C++ forbids converting a string constant to ‘char*’ [-Werror=write-strings]
45 | char *first = "Joseph ";
| ^~~~~~~~~
constructors_with_new.cpp:47:28: error: ISO C++ forbids converting a string constant to ‘char*’ [-Werror=write-strings]
47 | String name1(first), name2("Louis"), name3("Lagrange"), s1,s2;
| ^~~~~~~
constructors_with_new.cpp:47:44: error: ISO C++ forbids converting a string constant to ‘char*’ [-Werror=write-strings]
47 | String name1(first), name2("Louis"), name3("Lagrange"), s1,s2;
| ^~~~~~~~~~
cc1plus: all warnings being treated as errors


然后我找到了下面的答案

Why is conversion from string constant to 'char*' valid in C but invalid in C++

为了让它工作,我修改了上面的代码

  1. 在第二个构造函数中接收指向 const char 的指针 (String(char const *s))
  2. main() 中,通过更改名字“Joseph”的初始化,从 char * firstchar const * first ,正如 Jeremy Coffin 在对所提供链接的回答中所建议的那样

这样编译没有问题,输出如下

Joseph 
Louis
Lagrange
Joseph Louis
Joseph Louis Lagrange

我想知道这是否是解决此问题的最佳方法,或者您是否推荐一种不同的方法(也许是另一种不需要输入指向 const 类型的指针的方法 字符)。

最好的,

斯特凡诺

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com