c – 警告有关ofstream的暧昧,但不是ostream.有什么不同?

前端之家收集整理的这篇文章主要介绍了c – 警告有关ofstream的暧昧,但不是ostream.有什么不同?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这并不重要.但我很好奇这个警告何时出现.我真正的问题是为什么ostream和ofstream被区别对待.
  1. struct Test {
  2. int y;
  3. Test(int k) : y(k) {}
  4. };

使用这个简单的结构,编译器可以看到int可以转换为Test.

因此,我收到此代码的警告:

  1. std :: ofstream& operator<< (std :: ofstream& os,const Test& t)
  2. {
  3. os << t.y;
  4. return os;
  5. }

当它看到os<< t.y它不知道我是否要推送名为t.y的int,或者我是否要首先将int转换为Test然后再推送它.这看起来很奇怪,你会认为它更喜欢非转换的int重载流和&操作符LT;< (ofstream& os,int). g(Ubuntu 4.4.3-4ubuntu5)4.4.3:

  1. template_expl.cpp: In function std::ofstream& operator<<(std::ofstream&,const Test&)’:
  2. template_expl.cpp:15: warning: ISO C++ says that these are ambiguous,even though the worst conversion for the first is better than the worst conversion for the second:
  3. /usr/include/c++/4.4/bits/ostream.tcc:105: note: candidate 1: std::basic_ostream<_CharT,_Traits>& std::basic_ostream<_CharT,_Traits>::operator<<(int) [with _CharT = char,_Traits = std::char_traits<char>]
  4. template_expl.cpp:13: note: candidate 2: std::ofstream& operator<<(std::ofstream&,const Test&)

无论如何,解决此问题的一种方法是将Test中的构造函数标记为显式.我可以忍受这一点.但奇怪的是,如果ofstream被ostream取代,那么警告就会消失.知道为什么吗?

解决方法

正如警告告诉您的那样,对于ofstream,两种解释都需要转换:

> ofstream& – > ostream的和放;在static_cast< ostream&>(os)<< t.y,
> int – >在os<<<<的static_cast<试验>(t.y)

如果你使用ostream&直接,然后int解释不需要转换,因此是首选.

猜你在找的C&C++相关文章