【问题标题】:no known conversion from 'const value_type' to 'const void *' for 1st argument第一个参数没有从 'const value_type' 到 'const void *' 的已知转换
【发布时间】:2018-06-25 10:07:59
【问题描述】:

我正在尝试使用 std::cout 打印一组对,但它没有编译。我在 XCode 9 上使用 C++14。错误发生在 cout<<(*it);

错误:二进制表达式的操作数无效('ostream'(又名'basic_ostream')和'const value_type'(又名'const std::__1::pair'))

候选函数不可行:第一个参数没有从“const value_type”(又名“const std::__1::pair”)到“const void *”的已知转换;用 & 获取参数的地址

#include <iostream>
#include <set>
#include <map>
using namespace std;

template <class P, class Q> ostream& operator<<(ostream &out, pair<P,Q>& p)
{
    cout<<"["<<p.first<<","<<p.second<<"]";
    return out;
}

template <class T> ostream& operator<<(ostream &out, set<T> &S)
{
    cout<<"{";
    for(typename set<T>::iterator it = S.begin(); it != S.end(); it++) {
        cout<<(*it);   //Error occurs here
        if(next(it,1) != S.end()) cout<<",";
    }
    cout<<"}";
    return out;
}

int main() {
    set<pair<int,int>> s;
    s.insert({1,2});
    cout<<s;
    return 0;
}

【问题讨论】:

  • 你的重载应该通过 const 引用 std::pair。 (std::set 也一样)
  • 另外,在循环中使用++it 而不是it++
  • 谢谢!你能告诉我 ++it 和 it++ 的区别吗?对于整数,我一直使用后缀增量。
  • @PrayanshSrivastava 参见,例如,这里:stackoverflow.com/q/1077026/580083
  • @DanielLangr:或用于范围:cout &lt;&lt; "{"; auto sep = ""; for (const auto&amp; e : S) { cout &lt;&lt; sep &lt;&lt; e; sep = ","; } cout "}";

标签: c++ xcode c++11 c++14


【解决方案1】:

std::set 的迭代器是一个常量双向迭代器(至少从 C++11 开始)。因此,它的取消引用会导致对集合元素/键的持续引用(您可能不会直接修改集合键,这是有道理的,因为它会破坏底层数据结构 - 通常是某种形式的搜索树)。此引用表示一个常量左值参数,它可能不会绑定到非常量引用类型的参数(operator&lt;&lt; 中的p)。正如其他人已经建议的那样,请改用 const 引用作为参数。

【讨论】:

    猜你喜欢
    • 2022-07-29
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多