繁体   English   中英

二进制'operator':未找到采用'Fraction'类型的右侧操作数的运算符(或没有可接受的转换)

[英]Binary 'operator' : no operator found which takes a right-hand operand of type 'Fraction' (or there is no acceptable conversion)

[编辑]我正在写一个类型为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;
}

新答案:

您回答需要在Fraction.h中用这样的一行声明operator << ,并在使用它的代码之前#include "Fraction.h"

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

声明与定义的概念是C ++(和C)的基础,因此,如果您不了解该区别,请立即在网上搜索有关它的信息,以免进一步混淆。

编辑: 旧答案:

您确定您确实在执行file << arr[i]而不是file << somethingElse << arr[i]吗? 因为如果执行后者,则file << somethingElse的静态类型很可能是std::ostream&而不是std::ofstream& 在这种情况下,解决方案是将operator<< (..., Fraction)更改为接受(并返回)常规std::ostream&而不是std::ofstream&

编辑:另一种可能性:您需要确保从实例化Collection<Fraction>的位置可以看到operator<< (..., Fraction)的声明(即, operator<<的声明在其上方)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 二进制“ [”:找不到使用“初始化列表”类型的右侧操作数的运算符(或者没有可接受的转换) C2679 二进制“-=”:未找到采用“T”类型右侧操作数的运算符(或没有可接受的转换) 重载插入运算符:未找到采用“ unsigned int”类型的右侧操作数的运算符(或者没有可接受的转换) 错误C2679:binary&#39;=&#39;:找不到运算符,它接受类型&#39;std :: vector &lt;_Ty&gt; *&#39;的右手操作数(或者没有可接受的转换) 错误 C2679:二进制“&lt;&lt;”:未找到采用“RatNum”类型的右侧操作数的运算符(或没有可接受的转换) 错误C2679二进制&#39;=&#39;:找不到使用&#39;int&#39;类型的右侧操作数的运算符(或者没有可接受的转换) 错误:C2679二进制&#39;==&#39;:未找到采用类型为&#39;const std :: string&#39;的右侧操作数的运算符(或者没有可接受的转换 错误C2679:二进制&#39;&gt;&gt;&#39;:未找到采用&#39;const char [4]&#39;类型的右侧操作数的运算符(或没有可接受的转换)22 c ++错误c2679:二进制&#39;[&#39;:未找到采用&#39;SalesItem&#39;类型的右侧操作数的运算符(或者没有可接受的转换) 错误C2679:二进制&#39;&gt;&gt;&#39;:找不到哪个运算符采用&#39;std :: string&#39;类型的右手操作数(或者没有可接受的转换)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM