【发布时间】:2018-07-23 09:29:14
【问题描述】:
我有这样的代码,但我不断收到此错误:
A value of type "const char*" cannot be used to initialize an entity of type "char *"
发生了什么事?
我已经阅读了以下主题,但无法看到我的答案的任何结果,因为它们都是从 char 到 char* 或 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++