我正在用test.cpp
中的以下測試片段,嘗試掃描windowswave設備;
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-stylenull-terminated字符串的支持。為什么我會犯這個錯誤?
默認情況下,
UNICODE
宏是未定義的。這使得pzPname
字段在定義中是CHAR pzPname[MAXPNAMELEN]
。這就是錯誤產生的原因,因為std::wstring
試圖用char
數據而不是wchar_t
數據初始化。要解決這個問題,請在包含
Windows.h
文件之前放置一個#define UNICODE
語句,或者改用std::string
。