Errore di C2664 su utilizzando basic_string abc ( “ciao”) in VC ++ 9,0
-
22-08-2019 - |
Domanda
Ciao sulla compilazione di questo codice in Visual Studio 2008 ottengo il seguente errore
#include<iostream>
#include<string>
using namespace std;
void main()
{
basic_string<wchar_t> abc("hello world");
cout<<abc;
return;
}
C2664 errore: 'std :: basic_string <_Elem, _Traits, _Ax> :: basic_string (std :: basic_string <_Elem, _Traits, _Ax> :: _ Has_debug_it)': non può convertire il parametro 1 da 'const char [12] 'a 'std :: basic_string <_Elem, _Traits, _Ax> :: _ Has_debug_it'
C2679 errore: binario '<<': nessun operatore trovato che prende un operando a destra di tipo 'std :: basic_string <_Elem, _Traits, _Ax>' (o non v'è alcuna conversione accettabile)
che cosa è che sto facendo male?
Uno può aiutarmi a capire le cose che accadono dietro? Grazie
Soluzione
wchar_t specifica tipi di carattere di larghezza. Per impostazione predefinita, un puntatore const char a una stringa letterale non è ampia, ma si può dire al compilatore di trattarlo come un array di caratteri di larghezza per il prefisso con 'L'.
Quindi, solo per cambiare
basic_string<wchar_t> abc(L"hello world");
Altri suggerimenti
Prova:
Errore C2664:
basic_string<wchar_t> abc(L"hello world");
Errore C2679:
cout << abc.c_str();
(Dal momento che il compilatore non può / non fornirà un sovraccarico adatto ad ogni tipo di utente creato. Tuttavia, dal momento che questo è anche un tipo standard ovvero wstring
, ho guardato le intestazioni appropriate e non ha trovato operator<<
adeguato che richiede sia un string
o un wstring
).
e utilizzare int main
, in modo da avere:
int main(void)
{
basic_string<wchar_t> abc(L"hello world");
cout << abc.c_str() << endl;
return 0;
}
Anche se, è in realtà dovrebbe essere utilizzando std::wstring
invece di reinventare la ruota.
Il problema è che si sta mescolando carattere ampio e (stretto?) Tipi di carattere.
Per la vostra basic_string
, utilizzare uno:
// note the L"..." to make the literal wchar_t
basic_string<wchar_t> abc(L"hello world");
// note that basic_string is no longer wchar_t
basic_string<char> abc("hello world");
o equivalente:
// wstring is just a typedef for basic_string<wchar_t>
wstring abc(L"hello world");
// string is just a typedef for basic_string<char>
string abc("hello world");
E cambiare l'uscita in modo che corrisponda anche:
cout << abc; // if abc is basic_string<char>
wcout << abc; // if abc is basic_string<wchar_t>