ISO C++说这些是模棱两可的
ISO C++ says that these are ambiguous,
我必须重载移位运算符" <<",以便在控制台中写入和在二进制文件上写入。
我对 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::ofstream
或std::ifstream
.其次,因为一旦你使用了<<
,返回值是反正std::ostream
,所以operator<<
ofstream
永远不会被召唤。
当然,你对运算符的实现也违反了所有的规则。 您不会在运算符中打开或关闭文件;运算符用于格式化数据。 如果你愿意支持两种不同的格式,通常的方法是定义一个操纵者在它们之间进行选择,并让客户决定。(请参阅std::ios_base::xalloc()
和公司,了解放置附加状态。
- "Inverse SFINAE"避免模棱两可的过载
- 操作员C++的模棱两可的过载
- 模棱两可的重载模板
- 调用重载的"<大括号括起来的初始值设定项列表>"对于对来说就足够了是模棱两可的
- 模棱两可的 != reverse_iterator运算符
- SFINAE不能防止模棱两可的操作员过载吗?
- VSCode 说 std::chrono 是模棱两可的,如果运算符<<重载
- 为什么对模板的调用不模棱两可?
- 修复重载运算符的使用'+'模棱两可?
- 为什么同时覆盖全局新运算符和特定于类的运算符不是模棱两可的行为?
- Antlr4 C++访问模棱两可的分支
- 模棱两可的调用 - 模板化函数
- 在SESHAT中,对"元组"的引用是模棱两可的
- C++17 年与 Clang 的模棱两可的部分专业化
- gcc 中的模棱两可的运算符
- 将 NULL 转换为长不是模棱两可吗?
- C++ lambda 模棱两可的调用
- 带有模板的循环缓冲区在Keil MDK5上是模棱两可的错误?
- C++11 中对超载'ref(Select::Expressions::Code&)'的调用模棱两可
- 地图给出了一些模棱两可的价值