需要连接std:string + WCHAR移动gcc代码到Visual c++ 2010

Need to concatenate std:string + WCHAR moving gcc code to Visual C++ 2010

本文关键字:代码 gcc Visual 2010 c++ 移动 WCHAR 连接 std string      更新时间:2023-10-16

下面的代码不是我写的,它是开源的,不再受支持。我确实需要对它做一些改变,所以我安装了vc++ Express 2010,我已经设法解决了大部分问题,这个应用程序实际上是为Windows编写的,所以虽然它一直很棘手,但相当困难,我正在取得一些进展。

我被困在一个转换,我还没有完全得到vc++ 2010类型转换的处理,但这里的代码给我我最后的头痛…

path为std::string, cFileName为WCHAR。我相信我成功地将path转换为WCHAR,但随后是mEntries。Push_back有一个问题。我相信我需要做的是将cFileName转换为字符串,我已经搜索并尝试了许多不同的方法来做到这一点,但我要么语法错误,要么在vc++中不工作,要么我完全错过了其他东西。

这将是很高兴知道为什么它不工作,为什么有这么多不同的"类型"的字符串(我写SQL脚本,这是荒谬的),但在这一点上,我只需要帮助使它工作。

// Add files matching file spec to listing, returning number added. Each
// filename is prepended with its path, if one was supplied in file spec.
unsigned int DirList :: Add( const string & fspec ) {
// save path, if any
STRPOS lastslash = fspec.find_last_of( "\/");
string path = lastslash == STRNPOS ? "" : fspec.substr( 0, lastslash + 1 );
unsigned int count = 0;
WIN32_FIND_DATA fd;
HANDLE h = FindFirstFile( LPCWSTR(fspec.c_str()), & fd );
if ( h == INVALID_HANDLE_VALUE ) {
    return count;
}
do {
    mEntries.push_back(
        new WinDirEntry(
                path + fd.cFileName,    // add path back on
                fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY
        )
    );
    count++;
} while( FindNextFile( h, & fd ) );
FindClose( h );
return count;
}

错误信息是:

error C2782: 'std::basic_string<_Elem,_Traits,_Alloc> std::operator +(std::basic_string<_Elem,_Traits,_Alloc> &&,const _Elem *)' : template parameter '_Elem' is ambiguous
1>          ...microsoft visual studio 10.0vcincludestring(143) : see declaration of 'std::operator +'
1>          could be 'WCHAR'
1>          or       'char'
error C2784: 'std::basic_string<_Elem,_Traits,_Alloc> std::operator +(std::basic_string<_Elem,_Traits,_Alloc> &&,std::basic_string<_Elem,_Traits,_Alloc> &&)' : could not deduce template argument for 'std::basic_string<_Elem,_Traits,_Alloc> &&' from 'WCHAR [260]'
1>   ...microsoft visual studio 10.0vcincludestring(109) : see declaration of 'std::operator +'
error C2676: binary '+' : 'std::string' does not define this operator or a conversion to a type acceptable to the predefined operator

pathstd::string转换为std::wstring

std::string s("hello");
std::wstring ws;
ws.assign(s.begin(), s.end());

cFileName创建一个std::wstring,这样您就有相同类型的两个字符串来操作。

: assign()方法仅在从std::string转换为std::wstring时有效。反之亦然,并不适用于所有Unicode字符。找到这个codeguru.com论坛主题,讨论std::stringstd::wstring之间的转换:如何将字符串转换为wstring?

参考:

MSDN: std:: wstring

cplusplus.com std:: string/std:: wstring

我相信你的问题是因为std::string类型使用你的基本字符作为字符类型,+操作符没有为std::basic_string和宽字符数组定义。我认为Visual Studio支持std::wstring,如果将std::string替换为std::string,可能会使此工作顺利进行。

有几种不同的字符串因为有很多不同的方式来编码字符。ASCII, UTF-8,等等。并不是所有的都适合你的基本char*,在c++中,你并没有真正在很大程度上与之隔离。