【问题标题】:A value of type "const char*" cannot be used to initialize an entity of type "char *"“const char*”类型的值不能用于初始化“char *”类型的实体
【发布时间】:2018-07-23 09:29:14
【问题描述】:

我有这样的代码,但我不断收到此错误:

A value of type "const char*" cannot be used to initialize an entity of type "char *"

发生了什么事?
我已经阅读了以下主题,但无法看到我的答案的任何结果,因为它们都是从 charchar*char*char:
Value type const char cannot be used to initialize an entity of type char*Value of type char* cannot be used to initialize an entity of type "char"

#include <iostream>;
using namespace std;

int main() {
    int x = 0; //variable x created
    int cars (14);//cars is created as a variable with value 14
    int debt{ -1000 };//debt created with value 1000
    float cash = 2.32;
    double credit = 32.32;
    char a = 'a';//for char you must use a single quote and not double
    char* sandwich = "ham";
    return 0;
}

我正在使用 Visual Studio Community 2017

【问题讨论】:

  • const char* sandwich = "ham";
  • 错误信息的哪一部分你不明白?这意味着初始化(即表达式的右侧)的类型为const char*,而您声明了char*。只需按照它所说的修改声明的类型
  • 这是一个初学者的问题,但它不是一个坏问题。 int 对应于const int 就像char* 对应于char* const,而不是const char*,这一事实并不明显。
  • 就让 OP 知道,您应该避免以这种方式“修复”它。 char *sandwich = (char *)"ham"; 这仅是由于与 C 的向后兼容性而起作用,并且您无缘无故地抛弃了类型安全。

标签: c++


【解决方案1】:

没错。假设您有以下代码:

const char hello[] = "hello, world!";
char* jello = hello; // Not allowed, because:
jello[0] = 'J'; // Undefined behavior!

哎呀! const char* 是指向 const char 的非常量指针。如果您将其值分配给非 const char*,您将失去其 const 属性。

一个const 指向非常量char的指针将是一个char* const,如果你愿意的话,你可以整天初始化一个char*

如果你真的想的话,你可以使用const_cast&lt;char*&gt;(p) 来实现这一点,我偶尔也会这样做,但这通常表明存在严重的设计缺陷。如果您实际上让编译器发出指令以写入由字符串常量别名的内存,您会得到未定义的行为。 可能出错的许多事情之一是某些实现会将常量存储在只读内存中并崩溃。或者相同字节的内存可能会被重复用于多个目的,因为毕竟我们警告过您永远不要更改它。

顺便说一句,C 中的规则是不同的。这仅是为了向后兼容没有 const 关键字的早期 C 版本,并且您永远不应该编写对字符串常量使用非常量别名的新代码。

【讨论】:

    【解决方案2】:

    您需要将字符串文字类型设为 const,因为在 C++ 中它是 char 的常量数组,与 C 中它只是 char 的数组不同。您不能更改字符串文字,因此在 C++ 中将其设为 const 是首选,以提高安全性。这与从const char*char* 时必须使用显式转换的原因相同。它在 C++ 中仍然是技术上“允许的”,因为它在 C 中是允许的,这就是为什么它只是一个警告。这样做仍然是不好的做法。要修复警告,请将其设为const

    const char* sandwich = "ham";
    

    【讨论】:

    • 解释得很好。
    猜你喜欢
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    相关资源
    最近更新 更多