【问题标题】:binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)二进制 '==' :未找到采用 'std::string' 类型的左操作数的运算符(或没有可接受的转换)
【发布时间】:2012-03-04 22:31:14
【问题描述】:

我正在编写一个比较 std::strings 的模板类函数。 std::string 是模板参数。我的问题是我无法将两个 const 字符串与“==”运算符进行比较,然后我想我创建了两个非常量临时字符串变量来执行比较,但它仍然无法编译。不知道为什么。

VGraph 类被实例化为VGraph<std::string, std::string> myGraph;

template <typename V, typename E>
size_t VGraph<V, E>::find(const V& vert)
{
    V temp = vert; // (1)
    for (size_t i=0; i<graph.size(); i++)
    {
        V noneConst = graph[i].getVertex(); // (2)
        if (temp==noneConst)// I think broblem is here, and tried to fix using (1)(2)
            return i;
    }
    return graph.size();
}

相关功能原型

template <typename V, typename E>
const V& VVertex<V, E>::getVertex();

【问题讨论】:

  • 你使用的实例化中的 V 是什么?
  • 您可以完美地比较两个 const 字符串或两个 const 引用到一个字符串,您的问题一定出在其他地方。
  • @CaptainGiraffe:我假设错误消息是binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion)。否则这个问题的标题会很反直觉。
  • 比较两个 const std::strings 很好。你的问题在别处。你的代码(你在哪里实例化模板)#include ?
  • @CaptainGiraffe:错误消息不是声称左侧操作数是std::string吗?

标签: c++ templates constants


【解决方案1】:

你可能忘记了一个明确的:

#include <string>

std::string 类由您包含的另一个标头定义,但不是运算符 ==。

【讨论】:

  • 这是一个模板类。我需要包含实例类头文件吗?我想我需要在客户端代码中包含字符串,对吧?
  • 是的,你是对的。客户端代码忘记包含 。奇怪的是,当使用 VGraph 声明类实例而不包含 标头时它通过了编译,这让我忽略了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 2018-10-22
相关资源
最近更新 更多