运算符<<用std :: ostringstream问题覆盖[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

这是我的玩具计划。它无法编译错误消息“no operator <<匹配这些操作数”。任何帮助将不胜感激。

struct foo {
    std::string name;
};

std::ostringstream& operator<<(std::ostringstream& os, const foo& info)
{
    os << info.name;
    return os;
}

void insert(const foo& info)
{
    std::ostringstream os;
    os << "Inserted here " << info;  // don't work here
}

int main()
{
    foo f1;
    f1.name = "Hello";
    insert(f1);

}
c++
1个回答
4
投票

原因

os << "Inserted here " << info;

不起作用

os << "Inserted here "

返回std::ostream&,而不是std::ostringstream&

选项:

  1. 改变你的功能使用std::ostream而不是std::ostringstreamstd::ostream& operator<<(std::ostream& os, const foo& info) { ... }
  2. 改变你的使用方式。使用 os << "Inserted here "; os << info;

我强烈建议使用第一个选项。

© www.soinside.com 2019 - 2024. All rights reserved.