<目次>
(1) C++で「error: cannot initialize a variable of type ‘const unsigned char’ with an lvalue of type ‘const char [x]’」が発生した時の原因と対処
(1-1) エラーメッセージ&発生状況
(1-2) 原因
(1-3) 対策
(1) C++で「error: cannot initialize a variable of type ‘const unsigned char’ with an lvalue of type ‘const char [x]’」が発生した時の原因と対処
(1-1) エラーメッセージ&発生状況
error: cannot initialize a variable of type 'const unsigned char' with an lvalue of type 'const char [2]'
#include <iostream>
using namespace std;
string test(unsigned char uc){
string str(1, static_cast<char>(uc));
return str;
}
int main(void){
unsigned char uc = "a";
cout << test(uc) << endl;
}
(1-2) 原因
・文字列リテラル「”123″」は「const char[4]」の型
・文字列リテラル「”a”」なら「const char[2]」の型
(1-3) 対策
#include <iostream>
using namespace std;
string test(unsigned char uc){
string str(1, static_cast<char>(uc));
return str;
}
int main(void){
//# 修正箇所
unsigned char uc = 65;
cout << test(uc) << endl;
}
(OK例2)
#include <iostream>
using namespace std;
string test(unsigned char uc){
string str(1, static_cast<char>(uc));
return str;
}
int main(void){
//# 修正箇所
unsigned char uc = ‘a’;
cout << test(uc) << endl;
}
(図132)

●(参考)”a”と‘a’の違い
「’a’」=a 「”a”」=a\0
●(参考)unsigned char⇒stringへの変換
string (size_t n, char c);
string str(1, static_cast(uc));