二进制'operator':未找到采用类型为 'Fraction' 的右操作数的运算符(或者没有可接受的转换)
Binary 'operator' : no operator found which takes a right-hand operand of type 'Fraction' (or there is no acceptable conversion)
[EDIT]我正在编写一个具有类型参数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&
。
编辑:另一种可能性是:您需要确保operator<< (..., Fraction)
的声明在实例化Collection<Fraction>
的位置可见(即operator<<
的声明在其上方(。
相关文章:
- 错误 C2679:二进制"<<":未找到采用类型 'std::string_view' 的右侧操作数的运算符(或者没有可接受的转换)
- C2678 二进制 '==':未找到采用 'Card' 类型左操作数的运算符(或者没有可接受的转换)
- 二进制 '==':未找到采用 'Enemy' 类型左侧操作数的运算符(或者没有可接受的转换)
- 二进制 '=':未找到采用右操作数的运算符(或者没有可接受的对话)
- 错误 C2679:二进制'<<':找不到采用类型 'overloaded-function' 的右侧操作数的运算符(或者没有可接受的转换)
- 错误:C2679 二进制"==":未找到采用类型 'const std::string' 的右侧操作数的运算符(或者没有可接受的转换)
- 错误 C2678:二进制"+":未找到采用类型 'volatile A' 的左侧操作数的运算符(或者没有可接受的转换)
- 错误 C2679:二进制"<<":未找到采用类型 'mystring' 的右侧操作数的运算符(或者没有可接受的转换)
- 错误 C2679:二进制'>':找不到采用类型 'int' 的右侧操作数的运算符(或者没有可接受的转换)
- 错误 C2679 二进制"=":未找到采用类型 'int' 的右侧操作数的运算符(或者没有可接受的转换)
- 错误 C2679 二进制"=":未找到采用类型 'int' 的右侧操作数的运算符(或者没有可接受的转换)
- 运算符重载:简单添加...错误 C2677:二进制"+":未找到采用类型 ___ 的全局运算符(或者不存在可接受的转换)
- 错误 C2677:二进制'+=':找不到采用类型 'Movie' 的全局运算符(或者没有可接受的转换)
- 错误 C2678:'=='二进制:未找到采用类型 'CSchemaString' 的左操作数的运算符(或者没有可接受的转换)
- 错误 C2679:二进制"[":未找到采用类型为"const VerseKey"的右操作数的运算符(或者没有可接受的转换)
- 错误 C2678:二进制"==":找不到采用左操作数类型的运算符(或者没有可接受的转换)
- 错误 1 错误 C2679:二进制'<<':未找到采用类型 'rational' 的右侧操作数的运算符(或者没有可接受的转换)
- 二进制'operator':未找到采用类型为 'Fraction' 的右操作数的运算符(或者没有可接受的转换)
- 错误 C++ 2679(二进制">>":未找到采用类型 'const std::string' 的右侧操作数的运算符(或者没有可接受的转换))
- 二进制'operator':没有定义采用 'type' 型左操作数的运算符(或者没有可接受的转换)