为了在控制台中写入和在二进制文件中写入,我必须重载移位运算符“<<”..
我在 ostream 重载方面做得很好,而我在重载 fstream 时遇到了一些问题,这里是:
在我的标题中:
friend ostream &operator<<(ostream &, const Fotografia &);
friend fstream &operator<<(fstream &, const Fotografia &);
在我的 cpp 文件中:
fstream &operator<<(fstream & miofile, const Fotografia & sorgente)
{
//Open the file
miofile.open("data.dat", ios::binary | ios::app);
if(!miofile) cerr << "Can't open the file\n";
miofile << strlen(sorgente.Titolo);
miofile << endl;
miofile << sorgente.Titolo;
//I close the file
miofile.close();
return miofile;
}
这是我面临的错误:
在函数 `std::fstream& operator<<(std::fstream&, const Fotografia&)' 中:
ISO C++ says that these are ambiguous, even though the worst conversion for the first is better than the worst conversion for the second:
std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const char*) [with _Traits = std::char_traits<char>]
std::fstream& operator<<(std::fstream&, const Fotografia&)
到目前为止,我的理解是我刚刚创建的重载函数与标准 fstream << 之间存在歧义。 现在,我不明白为什么,因为我的重载函数应该只适用于“Fotografia”类(由我创建),而我正在尝试编写一个 char * 。
我认为我可以通过使用“::”范围调用 fstream 运算符来解决这个问题,但我不确定。
有人可以帮我吗? :)
编辑:
我正在发布 header 的代码和构造函数的代码
//Costruttore,distruttore,costruttore di copia,operatore di assegnazione.
Fotografia(char * titolo = "Untitled" , char * formato = ".jpeg");
~Fotografia() { delete [] Titolo; delete [] Formato;}
Fotografia(const Fotografia &);
Fotografia &operator=(const Fotografia &);
这是在 cpp 中:
Fotografia::Fotografia(char * titolo , char * formato)
{
Titolo = new char[strlen(titolo)+1];
strcpy(Titolo,titolo);
Formato = new char[strlen(formato)+1];
strcpy(Formato,formato);
} //Fine costruttore
最佳答案
去掉Fotografia
中的operator char*
,或者标记为explicit
。
此外,您可以插入任意的 basic_ostream
,而不是将代码限制为插入 fstream
。这对 fstream
仍然有效,并且会让您更灵活地使用其他形式的输出流。这也将消除错误。
关于c++ - ISO C++ 说这些是模棱两可的,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14610683/