在下面的代码中,变量gender被初始化为常量,但编译器给出错误,指出const char数据类型到char数据类型的转换无效。
#include<iostream>
using namespace std;
int main()
{
//initializing the variable
int a;
//declaring the variable
a = 13;
//data type: character, keyword: char, max size: 8 bits (1 byte)
char gender;
gender="Male";
cout<<"This is character data type: "<<gender<<endl;
//data type: integer, keyword: int, max size: 16 bits (2 bytes), range: -2^15-2^15 (-32768-32767)
int age = 19;
cout<<"This is int data type:"<<age<<endl;
//data type: integer, keyword: short int, max size: 16 bits (2 bytes), range: -2^15-2^15 (-32768-32767)
short int no = 12;
cout<<"This is short int data type: "<<no<<endl;
//data type: integer, keyword: long int, max size: 32 bits (4 bytes), range: -2^31-2^31 (-2147483648-2147483647)
long int larger = 21233487;
cout<<"This is long int data type: "<<larger<<endl;
//data type: floating point, keyword: float, max size: 32 bits (4 bytes)
float ab = 9.7;
cout<<"This is a floating point data type decimal: "<<ab<<endl;
//data type: floating point, keyword: double, max size: 64 bits (8 byte)
double ac = 1232434.7666;
cout<<"This is a double data type decimal:"<<ac<<endl;
//data type: floating point, keyword: long double, max size: 80 bits (10 byte)
long double ad = 1233284.79872;
cout<<"This is a long double data type decimal:"<<ad<<endl;
return 0;
}
这是我收到的错误:
C:\Users\Abdullah\Desktop\C++\Fundamentals_变量和数据 Types.cpp [错误]从“const char*”到“char”的转换无效 [-f允许]
我尝试在一行中初始化变量并在另一行中声明它,但没有任何改变。我检查了所有代码,但没有发现任何产生错误的地方。
员工类{ 私人的: 常量 int empID; 民众: 员工(int id):empID(id){
}
~Employee(){
}
};
您将性别声明为字符数据类型。 'char'只能存储1个字符。要解决此问题,请将声明修改为此。
char* gender;
gender = "Male";
您可能仍会收到警告,但代码现在可以正常工作了。