ISO C++说这些是模棱两可的

ISO C++ says that these are ambiguous,

本文关键字:模棱两可 C++ ISO      更新时间:2023-10-16

我必须重载移位运算符" <<",以便在控制台中写入和在二进制文件上写入。

我对 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 filen";
        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 运算符来解决这个问题,但我不确定。

有人可以在这里帮我吗?:)

编辑:

我正在发布标头的代码和构造函数的代码

         //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,并会给你更大的灵活性来使用其他形式的输出流。这也将消除错误。

std::fstream重载operator<<是没有意义的。首先,因为经验丰富的C++程序员几乎每次都使用 std::fstream ;他们使用std::ofstreamstd::ifstream.其次,因为一旦你使用了<<,返回值是反正std::ostream,所以operator<< ofstream永远不会被召唤。

当然,你对运算符的实现也违反了所有的规则。 您不会在运算符中打开或关闭文件;运算符用于格式化数据。 如果你愿意支持两种不同的格式,通常的方法是定义一个操纵者在它们之间进行选择,并让客户决定。(请参阅std::ios_base::xalloc()和公司,了解放置附加状态。