2

这是我的第一篇文章。

我阅读了很多主题,似乎我做得很好,但是当我尝试编译以下代码时再次出现上述错误:

// Header file

#include <fstream>
#include <ostream>
#include <string>

using namespace std;

class CLogger
{
private:
    ostream m_oStream;

public:
    CLogger(ostream& oStream);
    CLogger(const string sFileName);
};

// Implementation file

CLogger::CLogger(ostream& oStream) : 
m_oStream(oStream) // <-- Here is the problem?!
{
}

CLogger::CLogger(const string sFileName) :
    m_oStream(ofstream(sFileName.c_str()))
{   
}

你可以帮帮我吗?

非常感谢你!

4

2 回答 2

6
CLogger::CLogger(ostream& oStream) : // <-- Here is the problem?!
m_oStream(oStream)

问题不在第一行,而在第二行。

由于 memberm_oStream被声明为非引用,因此上面的第二行尝试复制oStream它是不可能的,因为复制构造函数已std::ostream被禁用private,这是您在错误消息“无法访问私有”中看到的成员。”

修复是这样的:

std::ostream * m_oStream; //declare it as pointer.
bool m_deleteStream;      //flag whether to delete m_oStream or not

现在这样做:

CLogger::CLogger(ostream& oStream) : 
m_oStream(&oStream), m_deleteStream(false)
{
}

CLogger::CLogger(const string sFileName) :
m_oStream(new std::ofstream(sFileName)), m_deleteStream(true)
{
  //Note : in C++03, you've to pass sFileName.c_str() to 
  //the constructor of std::ostream   
}

然后你要把析构函数写成:

~CLogger()
 {
    if ( m_deleteStream )
    {
        delete m_oStream;
    }
 }

重要的一点:由于这是一个资源管理(记录器)类,因此使其不可复制是一个好主意,因为复制对于记录器实例没有意义。

于 2012-12-19T15:43:40.260 回答
0

m_oStream(ofstream(sFileName.c_str()))

你用它构建一个ofstream并复制构建你m_oStream的。写吧

m_oStream(sFileName.c_str())

流既不是可复制构造的,也不是可复制分配的,尽管它们是可移动类型,所以我猜你在这个例子中没有使用 C++11。

出于同样的原因,

CLogger::CLogger(ostream& oStream) : 
    m_oStream(oStream)

不会工作。您不能复制,只能移动(在 C++11 中)或持有某种形式的引用。


边注:

从您的示例中,您是否这样做并不完全清楚,但不要忘记在头文件中包含保护。

于 2012-12-19T15:43:26.947 回答