问题描述
我正在尝试使用 test.cpp
中的以下测试片段通过 windows wave 设备进行扫描;
using namespace std;
#include <string>
#include <vector>
#include <Windows.h>
int main ()
{
int nDeviceCount = waveOutGetNumDevs();
vector<wstring> sDevices;
WAVEOUTCAPS woc;
for (int n = 0; n < nDeviceCount; n++)
if (waveOutGetDevCaps(n,&woc,sizeof(WAVEOUTCAPS)) == S_OK) {
wstring dvc(woc.szPname);
sDevices.push_back(dvc);
}
return 0;
}
使用 gcc version 8.1.0 (i686-posix-dwarf-rev0,Built by MinGW-W64 project)
在 PowerShell 中编译,我收到此错误:
PS xxx> g++ .\test.cpp -c
.\test.cpp: In function 'int main()':
.\test.cpp:14:27: error: no matching function for call to 'std::__cxx11::basic_string<wchar_t>::basic_string(CHAR [32])'
wstring dvc(woc.szPname);
我认为 wstring
构造函数包括对 c 样式空终止字符串的支持。为什么我会收到此错误?
解决方法
默认情况下,UNICODE
宏是未定义的。这使得 pzPname
字段在定义中变为 CHAR pzPname[MAXPNAMELEN]
。这就是出现错误的原因,因为 std::wstring
试图用 char
数据而不是 wchar_t
数据进行初始化。
要解决此问题,请在包含 #define UNICODE
文件之前放置一个 Windows.h
语句,或者改用 std::string
。