在 C++ 中初始化为常量的变量

Variable initialized as a constant in C++

提问人:Muhammad Abdullah 提问时间:10/7/2023 最后编辑:wohlstadMuhammad Abdullah 更新时间:10/7/2023 访问量:72

问:

在下面的代码中,变量 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\03_Variables 和数据 类型.cpp [错误] 从“常量字符*”到“字符”的转换无效 [-fpermissive]

我尝试在一行中初始化变量并在另一行中声明它,但没有任何变化。我浏览了所有代码,但没有发现任何产生错误的内容。

C++ 字符串 变量 控制台

评论

2赞 Yacov Dlougach 10/7/2023
你把它声明为单字符类型,所以你可以这样写: 要使其成为多字符,您需要使用数组类型:char gender = 'm';const char* gender = "Male";
0赞 wohlstad 10/7/2023
旁注:为什么“使用命名空间标准”被认为是不好的做法?

答:

0赞 0xAR33B 10/7/2023 #1

您正在将性别声明为字符数据类型。“char”只能存储 1 个字符。若要解决此问题,请将声明修改为 this。

const char *gender;
gender = "Male";

const char *gender = "Male";

您可能仍会收到警告,但代码现在可以正常工作。

评论

1赞 Paul Sanders 10/7/2023
const char *,应该是
0赞 0xAR33B 10/7/2023
@PaulSanders 是的,你是对的,它应该是 const char*
0赞 Muhammad Abdullah 10/7/2023
谢谢,是的,代码正在运行,也没有警告。
0赞 ahmedembedded 10/7/2023 #2
char gender[] = "Male";

使用此行代替 char gender;gender=“Male”,它将形成一个 char 数组/指针。