小编M. *_*ock的帖子

在C ++中将char *转换为const char *

如何在C ++中转换char*为const char*?为什么程序1可以运行,但是程序2不能运行?

编1(工作):

char *s = "test string";
const char *tmp = s;
printMe(tmp);

void printMe(const char *&buf) {
    printf("Given Str = %s", buf);
}
Run Code Online (Sandbox Code Playgroud)

编2(无效)

char *s = "test string";
printMe((const char *)s);     // typecasting not working

void printMe(const char *&buf) {
    printf("Given Str = %s", buf);
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误:

x.cpp:10:15: warning: conversion from string literal to 'char *' is 
deprecated [-Wc++11-compat-deprecated-writable-strings]
char *s = "test string";
          ^
x.cpp:12:5: error: no matching function for call …
Run Code Online (Sandbox Code Playgroud)

c++ pointers casting const reference

5
推荐指数
1
解决办法
7502
查看次数

标签 统计

c++ ×1

casting ×1

const ×1

pointers ×1

reference ×1