【问题标题】:Binary 'operator' : no operator found which takes a right-hand operand of type 'Fraction' (or there is no acceptable conversion)二进制“运算符”:未找到采用“分数”类型的右手操作数的运算符(或没有可接受的转换)
【发布时间】:2016-11-07 17:17:12
【问题描述】:

[编辑] 我正在编写一个带有类型参数T 的模板类。在该类的一个函数成员中,类型为T 的变量预计将写入std::ofstream 对象。在我使用自定义类型参数Fraction 实例化此类之前,一切都很好。尽管我确实重载了operator <<,但仍会发生错误。

// collection.h
#include <fstream>
template<typename T>
class Collection
{
public:
    void writeToFile();
private:    
    T val;
};

template<typename T>
inline void Collection<T>::writeToFile()
{
    std::ofstream file("output.txt");
    file << val;

}

// Fraction.cpp
#include <iostream>
std::ostream& operator << (std::ostream& str, const Fraction& f)
{
    std::cout << "Hello";
    return str;
}

【问题讨论】:

标签: c++ templates


【解决方案1】:

新答案:

您的回答需要在Fraction.h 中声明operator &lt;&lt;,并在使用它的代码之前声明#include "Fraction.h"

std::ostream& operator << (std::ostream& str, const Fraction& f);

声明与定义的概念是 C++(和 C)的基础,因此,如果您不了解区别,请立即在网络上搜索,以免造成更多混淆。

编辑:旧答案:

你确定你真的只是在做file &lt;&lt; arr[i] 而不是file &lt;&lt; somethingElse &lt;&lt; arr[i]?因为如果你做后者,那么file &lt;&lt; somethingElse 的静态类型很可能是std::ostream&amp; 而不是std::ofstream&amp;。在这种情况下,解决方案是将operator&lt;&lt; (..., Fraction) 更改为接受(并返回)一般std::ostream&amp; 而不是std::ofstream&amp;

编辑:另一种可能性:您需要确保 operator&lt;&lt; (..., Fraction) 的声明从您实例化 Collection&lt;Fraction&gt; 的位置可见(即 operator&lt;&lt; 的声明在其上方)。

【讨论】:

  • 你真的应该等待 OP 提供minimal reproducible example。目前这些只是猜测。
  • @NathanOliver:如果我愿意,我可以猜到!我选择浪费的只是我的时间。
  • 我刚刚编辑了问题,使其更清晰、更准确。
  • @Rickie 我已经更新了我的答案,尽管没有看到Fraction.h 的内容(如果存在这样的文件),这仍然是猜测。
猜你喜欢
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多