![](/img/trans.png)
[英]binary '[': no operator found which takes a right-hand operand of type 'initializer list' (or there is no acceptable conversion)
[英]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.