【问题标题】:C++ compile error with iostreamiostream 的 C++ 编译错误
【发布时间】:2011-01-17 15:03:25
【问题描述】:

我正在使用 fstream,但出现了一些错误。

这是我所拥有的:

class CLog
{
    void printOn(std::ostream& dbg) const;
}

void operator>>(const CLog& s, std::ofstream& dbg)
{
    s.printOn(dbg);
}

但是当我编译时出现以下错误:

error C2664: 'printOn' : cannot convert parameter 1 from 
'class std::basic_ofstream<char,struct std::char_traits<char> >' to 
'class std::basic_ostream<char,struct std::char_traits<char>  > &' 
A reference that is not to 'const' cannot be bound to a non-lvalue

我以为 ofstream 继承自 ostream 那为什么不可能呢?

谢谢

【问题讨论】:

  • 阿格!发现了一个丢失的#include &lt;fstream&gt;。编译器的输出多么愚蠢。谢谢大家

标签: c++ inheritance iostream


【解决方案1】:

更正确的输出运算符声明如下:

std::ostream& operator << (std::ostream& dbg, const CLog& s)
{
    s.printOn(dbg);
    return dbg;
}

【讨论】:

  • 不应该是运营商>>
  • 你可以在 CLog 类中声明为友元操作。
【解决方案2】:

公开 printOn 并包含 fstream 标头:)。

#include <fstream>
class CLog
{
public:
    void printOn(std::ostream& dbg) const
    {

    }
};

std::ofstream & operator<<( std::ofstream& dbg, const CLog& s)
{
    s.printOn(dbg);
}

【讨论】:

  • printOn 是公开的 fstream 丢失了谢谢 :)。但是为什么在这种情况下编译器输出如此无用。
  • 另外值得注意的是,您在 operator>> 中交换了参数的顺序,这对于提取运算符很重要,即流位于左侧。如果你真的打算让它成为一个运算符
【解决方案3】:

我建议发布 完整 代码,以便重现问题。我没有:

#include <fstream>

class CLog
{
public:
    void printOn(std::ostream& dbg) const;
};

void operator>>(const CLog& s, std::ofstream& dbg)
{
    s.printOn(dbg);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    相关资源
    最近更新 更多