0

コードをコンパイルしようとすると、次のエラーが発生します。

1>  c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/ostream: In constructor 'Log::Log(const char*)':
1>c:\mingw\bin\..\lib\gcc\mingw32\4.6.2\include\c++\ostream(363,7): error : 'std::basic_ostream<_CharT, _Traits>::basic_ostream() [with _CharT = char, _Traits = std::char_traits<char>]' is protected
1>C:\Users\Adam\Documents\cs\cs176b\hw2\ftp\ftp\log.cpp(6,26): error : within this context

理由はよくわかりませんが、自分で使用している ostream コードを作成しなかったため、ここで提案されているものを使用しました:ファイルまたは cout に ostream を作成する適切な方法

私のコードは以下のとおりです。必要に応じてさらに情報を提供してください。

// log.h
#include <string>
#include <fstream>

#ifndef LOG_H_
#define LOG_H_

class Log 
{
    public:
        enum Mode { STDOUT, FILE };

        // Needed by default
        Log(const char *file = NULL);
        ~Log();

        // Writing methods
        void write(char *);
        void write(std::string);
    private:
        Mode mode;
        std::streambuf *buf;
        std::ofstream of;
        std::ostream out;
};

#endif


// log.cpp
#include "log.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>

Log::Log(const char *file)
{
    if (file != NULL)
    {
        of.open(file);
        buf = of.rdbuf();
        mode = FILE;
    }
    else
    {
        buf = std::cout.rdbuf();
        mode = STDOUT;
    }

    // Attach to out
    out.rdbuf(buf);
}

Log::~Log()
{
    if (mode == FILE)
        of.close();
}

void Log::write(std::string s)
{
    out << s << std::endl;
}

void Log::write(char *s)
{
    out << s << std::endl;
}
4

2 に答える 2

3

std::ostream::ostream()コンストラクターは protectedです。つまり、コンストラクターはその派生クラスによってのみ呼び出すことができますが、それを囲むクラスによっては呼び出すことができません。

エラーを修正するには、 member を初期化しますout

の唯一の公開コンストラクターstd::ostreamは、 a を受け入れますstd::streambuf*。例:

Log::Log(const char *file)
    : out(std::cout.rdbuf())
// ...

デストラクタはそのメンバーの割り当てを解除しないため、 astd::ostreamを からのバッファで初期化しても安全であることに注意してください。std::cout.rdbuf()std::ostream::~ostream()std::streambuf*

または、NULL/で初期化することもできますnullptr。この場合、ストリームに何も出力しないように注意してください。これはNULL、定義されていない動作につながる逆参照を試みるためです。ほとんどの場合、単に でクラッシュしSIGSEGVます。

于 2013-02-08T23:15:35.513 に答える
0

デビッドが言ったことの延長として:

ostream出力ストリームの単なる「フレーム」であり、出力ストリーム (抽象クラス) の基本機能の定義です。何もせず、実装されていません。

coutおそらくに書き込もうとしましたか?coutで定義されiostreamています。定義する必要はありません。そのまま使用してください。

于 2013-02-08T23:14:22.280 に答える