C++ファイルのオープンのエラー(error C2248)


くろのすけ  2007-01-10 06:16:32  No: 64184

くろのすけです。

↓エラーの原因が分かりません。ファイルストリームの
宣言の部分が原因のようですが、何かいけないことをしているでしょうか?msdnでも検索しましたがよくわかりません。

c:\program files\microsoft visual studio 8\vc\include\fstream(802)
 : error C2248: 'std::basic_ios<_Elem,_Traits>::basic_ios' :
 private メンバ (クラス 'std::basic_ios<_Elem,_Traits>' で宣言され
ている) にアクセスできません。

//Class_Text.h
#include <string>
#include <iostream>
using namespace std;

class TextFile
{
  string strFilePath;          /* ファイルパス */
  TextFile ( const TextFile& );
  TextFile& operator=( const TextFile& );
public:
  TextFile ( string cFilepath ) : strFilePath( cFilepath ) {}

  ifstream& OpenReadMode( )
  {
    std::locale::global(std::locale("japanese"));  
    ifstream fin( strFilePath.c_str(), ios::in);  
    std::locale::global( std::locale("C") );    

    if (!fin) { cout << "Open Error\n"; }
    return fin;
  }

  ofstream OpenWriteMode( )
  {
    std::locale::global(std::locale("japanese"));  
    ofstream fout( strFilePath.c_str(), ios::out);  
    std::locale::global( std::locale("C") );    

    if (!fout) { cout << "Open Error\n"; }

    return fout;
  }

  void Close( ifstream fin ){ fin.close(); }

  void Close( ofstream fout ){ fout.close(); }

};


επιστημη  2007-01-10 07:42:21  No: 64185

ローカル変数の参照返してどーするよ!?


くろのすけ  2007-01-10 18:33:39  No: 64186

間違いです。
>ifstream& OpenReadMode( )
      ↓  
ifstream OpenReadMode( )
です。(ただ再度コンパイルしましたがエラーの原因ではありませんでした。)


Blue  2007-01-10 18:48:08  No: 64187

ifstream のデストラクタでファイルを閉じてしまっているからダメなんじゃ。

イメージとしてこんな感じ。

#include <iostream>
#include <cstdio>

struct Foo
{
    FILE* fp;
    Foo() { fp = fopen("test.txt", "r"); }
    ~Foo() { fclose(fp); }

    char* ReadLine(char* buff, int len)
    {
        return fgets(buff, len, fp);
    }
};

Foo Test()
{
    Foo f;
    return f;
}

int main()
{
    Foo f = Test();
    char buff[256];

    f.ReadLine(buff, sizeof(buff)); // fcloseしたFILE*の変数を使うことになる

    return 0;
}


tetrapod  2007-01-10 19:34:31  No: 64188

要するに basic_Xstream のオブジェクトのコピーは禁じられているのです。
ifstream is("file.txt");
ifstream dup(is); // Error! Copy constructor is private

提示の例では
Open*Mode : fstream を return しようとしています。
Close: fstream を引数に渡そうとしています。
関数の値返却/引数受け渡しは文法解釈上コピーであるため、エラー。

そもそも何がしたいのかが提示コードから読み取れませんが
stream を class TextFile のメンバに持つのが正しいと思う。
class TextFile {
  ifstream fin;
  ofstream fout;
public:
  bool OpenWrite(...) { ... }
  bool OpenRead(...) { ... }
  bool Close() { ... }
};


※返信する前に利用規約をご確認ください。

※Google reCAPTCHA認証からCloudflare Turnstile認証へ変更しました。






  このエントリーをはてなブックマークに追加