在C++中将tstring转换为string

3

这是一个使用Visual Studio 6编译的程序片段。但是在使用Visual Studio 2013编译后,我在以下行收到了错误。 我已经将错误语句粘贴在下面。

这在头文件中声明。

public:
Serial(tstring &commPortName, int bitRate = 115200, char *Name = NULL);

这是源文件中的内容

string COMport;

    cout << "Enter the COM port (eg. COM1): ";
    cin  >> COMport;

    tstring commPortName(COMport); //**ERROR AT HERE**
    Serial serialDEVICE(commPortName, 115200, "DEVICE");

我遇到了以下错误。
Error   1   error C2664: 
'std::basic_string<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>::   
basic_string(std::initializer_list<_Elem>,const std::allocator<wchar_t> &)'  
: cannot convert argument 1 from 'std::string' to 'const

第二个错误:
IntelliSense: no instance of constructor "std::basic_string<_Elem, _Traits,    
_Alloc>::basic_string [with _Elem=wchar_t, 
_Traits=std::char_traits<wchar_t>, _Alloc=std::allocator<wchar_t>]" matches
 the argument list argument types are: (std::string)

我需要将tstring转换为string吗,以消除这个错误?
1个回答

5

tstring 不是标准的 C++ 类型,但我假设你的项目中有类似于以下内容的东西:

#ifdef UNICODE
#define tstring std::wstring
#else
#define tstring std::string
#endif

在使用Unicode版本的Visual Studio进行编译时,默认情况下会将定义为,这意味着需要宽字符串来初始化它。由于被定义为ANSI字符串(std :: string),而不是,所以构建失败,因为两种类型不能直接转换。
你可能应该将项目改回ANSI(多字节)版本(至少在短期内),因为毫无疑问,在没有全面的代码审查的情况下,你会遇到其他兼容性问题。你可以在项目属性对话框的通用部分中使用字符集选项来实现这一点。

2
不,你是正确的,tstring 是一个持续的灾难,由一堆字符串处理函数和宏组成,旨在撤销微软最初未遵循 C++ 编程标准所造成的损害 - 大概是因为他们想要“锁定”代码只能在微软编译器下编译。 - Owl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接