繁体   English   中英

C ++ wifstream:不兼容的类型char const *,wchar_t const *

[英]C++ wifstream: Incompatible type char const*, wchar_t const*

我下面的一个DirectX 3D模型加载教程这里和我一起去,我测试代码的一小部分。 要加载我的.obj文件,我需要使用一个宽文件流,教程提示初始化一个我需要传入一个宽字符串的新流。

我已经偏离了教程,因为我希望将演示的串行实现转换为一个整洁的OO包,但是当我尝试初始化我的file变量以进行读取时,我得到一个incompatible type char const* to wchar_t const* error

我该如何解决这个问题?

class Stream {
private:
    std::wifstream file;
public:
    bool open_file(std::wstring &filename) {
        file = std::wifstream(filename.c_str());    // error thrown here.
    }
};

从main调用open函数。

std::wstring filename = "test_read.txt";
if(d.open_file(filename))
{
    // Do read processing here
}

提前致谢。

首先,您正在尝试分配流 ,但您无法做到这一点。 流不是容器,而是数据流 因此无法复制或分配它们。 相反,您可以使用流对象的open成员函数:

class Stream {
private:
    std::wifstream file;
public:
    bool open_file(std::wstring &filename) {
        file.open(filename.c_str());
    }
};

然后我们回到文件名的问题。 你正在阅读的教程是错误的 以下重载可用于所有basic_ifstream实例化

void open( const char *filename,
           ios_base::openmode mode = ios_base::in );
void open( const std::string &filename,                                  
           ios_base::openmode mode = ios_base::in );

也就是说,无论流的CharT如何,只接受诚实的const char*std::string作为文件名。

更有可能的是,本教程基于Microsoft标准库实现提供的非标准扩展进行了假设,这增加了使用const wchar_t*重载。 如果您希望编写可移植代码,请忽略这些重载。

最后,您目前没有从open_file返回任何内容,这会导致未定义的行为。

您更正后的代码应如下所示:

class Stream {
private:
    std::wifstream file;
public:
    bool open_file(const std::string& filename) {
        file.open(filename);    // file.open(filename.c_str()) in C++03
        return file.is_open();
    }
};

std::wifstream在其构造const char* 你不能从wstring传递c_str ,因为wstring返回一个const charT* 这些类型不兼容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM