【问题标题】:I'm getting error C2664 on some I/O code我在某些 I/O 代码上收到错误 C2664
【发布时间】:2010-02-26 18:39:58
【问题描述】:
void BinaryTree::InitializeFromFile(string Filename){
ifstream inFile;
inFile.open(Filename, fstream::binary);
if(inFile.fail()){
    cout<<"Error in opening file "<<Filename;
    return;
}
 for(int i=0;i<=255;i++) Freq[i]=0;
  char c;
  inFile.get(c);
  while(!inFile.eof()){
    Freq[c] ++;
    inFile.get(c);
  }
}  



HuffmanTree.cpp(293) : error C2664: 'void std::basic_ifstream<_Elem,_Traits>::
open(const wchar_t *,std::ios_base::openmode,int)' : cannot convert parameter 1 
from 'std::string' to 'const wchar_t *'
1>    with
1>    [
1>        _Elem=char,
1>        _Traits=std::char_traits<char>
1>    ]
1>    No user-defined-conversion operator available that can perform this 
      conversion, or the operator cannot be called

第 293 行是inFile.open(Filename, fstream::binary);

【问题讨论】:

    标签: c++ visual-c++ huffman-code


    【解决方案1】:

    请改用Filename.c_str() - open() 不会将std::string 作为文件名的参数。

    【讨论】:

      【解决方案2】:

      ifstream::open的调用中使用Filename.c_str()而不是Filename

      【讨论】:

        【解决方案3】:

        有点令人困惑的是,ifstream::open 采用 C 字符串,而不是 C++ std::string。将行更改为:

        inFile.open(Filename.c_str(), fstream::binary);
        

        我不知道为什么 C++ 标准库的设计者会做出这样的选择,但是你去吧。

        【讨论】:

        • 因为一般来说C++标准库的设计是不强制用户使用他们不想使用的特性,比如std::string。
        • 很公平,但甚至不提供接受std::string 的重载仍然让我觉得有点奇怪。
        【解决方案4】:

        ifstream ctor 需要 const char *。使用Filename.c_str()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-06
          • 1970-01-01
          • 1970-01-01
          • 2020-06-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多