【问题标题】:'+' cannot add two pointers, but just printing an int and an explicit string?'+' 不能添加两个指针,而只是打印一个 int 和一个显式字符串?
【发布时间】:2014-06-19 00:44:17
【问题描述】:

我正在尝试使用数组来跟踪不同类型项目的总数(最多 50 种类型)。当我想打印总计时,我收到一条错误消息,提示“'+' 无法添加两个指针”。我认为问题出在我的总计数组上,但我无法弄清楚。以下是我的代码示例:

  string printSolution()
  {
  int totals[50];

  string printableSolution = "";

  for (int k = 0; k < itemTypeCount; k++)
  {
      totals[k] = 0;
  }

  for (int i = 0; i < itemCount; i++)
  {
      totals[items[i].typeCode]++;
  }

  for (int a = 0; a < itemTypeCount; a++)
  {
      printableSolution.append("There are " + totals[a] + " of Item type " + (a + 1) + ". \n");
  }


}

【问题讨论】:

标签: c++ string visual-c++


【解决方案1】:

字符串文字"Foo" 属于const char*,即指针类型。

要了解会发生什么:

"There are " + totals[a] + " of Item type " + (a + 1) + ". \n"

我们来看一个表达式:

"0123456789" + 5 

这实际上只是从开始偏移了 5 个字节,所以变成:

"56789" 

所以一个表达式:

"0123456789" + 5 + "foo"

变成:

"56789" + "foo"

作为指针,这没有定义。

你真正想要的是字符串连接;这可以使用std::string 来实现。

我们可以这样写:

   std::string("56789") + "foo"

这会生成一个std::string,其值为:"56789foo",如您所愿。

但是:

 std::string("0123456789") + 5 

也没有定义。你需要使用:

std::string("0123456789") + std::to_string(5)

所以,最后你想要:

std::string("There are ") + std::to_string(totals[a]) + " of Item type " + std::to_string(a + 1) + ". \n"    

请注意,现在您不需要将所有"" 显式转换为std:string,因为一旦您进行了一个隐式类型转换,就会处理operator+ 中的另一个操作数。但是,添加它们不会有任何害处:

std::string("There are ") + std::to_string(totals[a]) + std::string(" of Item type ") + std::to_string(a + 1) + std::string(". \n")

【讨论】:

    【解决方案2】:

    问题出在这里:

    "There are " + totals[a] + " of Item type " + (a + 1) + ". \n"
    

    意思是char* + int + char* + int + char*。您需要单独打印出来或将int 更改为std::string

    【讨论】:

      【解决方案3】:

      改用 C++ 样式的格式:

      std::ostringstream oss;
      oss << "There are " << totals[a] << " of Item type " << (a + 1) << ". \n";
      printableSolution += oss.str();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-27
        • 2019-08-02
        • 2017-12-13
        相关资源
        最近更新 更多