【问题标题】:Set new name for football club in c++在 C++ 中为足球俱乐部设置新名称
【发布时间】:2020-07-20 09:13:03
【问题描述】:

我的任务是设置足球俱乐部的对象并更改其名称。

在课堂上:

Club(string _name, string _colour) :
        name(_name), colour(_colour) {}
void newName(char* newName)
{
   strcpy(name, newName);
}

主要:

Klub k1("Manchester", "red");
k2.newName("Arsenal");

我收到此错误: 错误 C2664 'std::string Club::newName(char *)': 无法将参数 1 从 'const char [7]' 转换为 'char *'

我包含了 cstring

【问题讨论】:

  • 为什么不使用std::string 作为参数? strcpy 不适用于 std::string 类型。
  • 一旦你使用std::string,就没有理由对字符串使用char*
  • 字符串 newName(char* Name) { name= Name; }
  • void newName(std::string n) { name = n;}
  • 您传递给函数的字符串文字 "Arsenal" 是一个指向 const char 的指针。这就是编译器抱怨的原因。

标签: c++ string replace


【解决方案1】:

如果您想使用字符串文字作为函数的参数,请将 void newName(char*) 替换为 void newName(const char*)。我建议传递const std::string& 而不是char*

【讨论】:

    【解决方案2】:

    您可以直接分配给std::string 对象,但在其上使用strcpy 没有意义。由于您可以从char * 构造std::string,您应该这样做:

    ...
    void newName(const char* newName)
    {
       name = std::string(newName);
    }
    

    此外,由于您从不更改输入参数,因此应将其设为const

    【讨论】:

      【解决方案3】:
      string newName(string Name)
          {
              name= Name;
              return name;
              
          }
      

      【讨论】:

      • 您至少应该将Name 声明为const。这将允许编译器删除一个副本。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-05
      • 2022-01-20
      相关资源
      最近更新 更多