从焦炭隐式转换**为const char ** [英] Implicit conversion from char** to const char**

查看:125
本文介绍了从焦炭隐式转换**为const char **的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我的编译器(GCC)犯规隐式地从的char ** 转换为为const char **

Thie以下code:

 的#include<&iostream的GT;无效打印(为const char **的事情){
    性病::法院LT&;<事[0]&下;&下;的std :: ENDL;
}INT主(INT ARGC,字符** argv的){
    打印(ARGV);
}

提供了以下错误:

  oi.cpp:在函数'主INT(INT,CHAR **):
oi.cpp:8:12:错误:从无效的转换的char **'到'为const char **'[-fpermissive]
oi.cpp:3:6:错误:初始化的参数1'无效打印(为const char **)[-fpermissive]


解决方案

这样的转换可以让你把一个为const char * 进入你的阵列的char * ,这将是不安全的。在打印你可以这样做:

 的事情[0] =ABC;

现在的argv [0] 将指向字符串文字不能被修改的,而,预计是非const的(的char * )。因此,对于类型安全这种转换是不允许的。

Why my compiler(GCC) doesnt implicitly cast from char** to const char**?

Thie following code:

#include <iostream>

void print(const char** thing) {
    std::cout << thing[0] << std::endl;
}

int main(int argc, char** argv) {
    print(argv);
}

Gives the following error:

oi.cpp: In function ‘int main(int, char**)’:
oi.cpp:8:12: error: invalid conversion from ‘char**’ to ‘const char**’ [-fpermissive]
oi.cpp:3:6: error:   initializing argument 1 of ‘void print(const char**)’ [-fpermissive]

解决方案

Such a conversion would allow you to put a const char* into your array of char*, which would be unsafe. In print you could do:

thing[0] = "abc";

Now argv[0] would point to a string literal that cannot be modified, while main expects it to be non-const (char*). So for type safety this conversion is not allowed.

这篇关于从焦炭隐式转换**为const char **的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆