C2440:"=":无法从"const char [9]"转换为"char *" [英] C2440: '=': cannot convert from 'const char [9]' to 'char*'

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

问题描述

我正在研究一个用C ++编写的Qt5项目.构建项目会出现错误:

I am working on a Qt5 project written in C++. Building the project gives an error:

C2440:'=':无法从'const char [9]'转换为'char *'

C2440: '=': cannot convert from 'const char [9]' to 'char*'

哪个指向下面的代码行:

Which points to the line of code below:

port_name= "\\\\.\\COM4";//COM4-macine, COM4-11 Office

SerialPort arduino(port_name);
if (arduino.isConnected())
    qDebug()<< "ardunio connection established" << endl;
else
    qDebug()<< "ERROR in ardunio connection, check port name";
//the following codes are omitted ....

这是什么问题,我该如何解决?

What is the problem here, and how can I correct it?

推荐答案

字符串文字是C ++中的常量数据(编译器会在可能的情况下将其存储在只读内存中).

String literals are constant data in C++ (compilers tend to store them in read-only memory when possible).

在C ++ 11和更高版本中,您不能再将字符串文字直接分配给 pointer-to-non-const-char (char*) 1 .

In C++11 and later, you can no longer assign a string literal directly to a pointer-to-non-const-char (char*) 1.

1:尽管某些C ++ 11编译器可能允许它作为向后兼容的非标准扩展,但可能需要通过编译器标志手动启用.

因此,您需要将port_name声明为 pointer-to-const-char (const char *char const *).但是,当将其传递给SerialPort()时,您将不得不将其强制转换回非常量char*:

So, you need to declare port_name as a pointer-to-const-char instead (const char * or char const *). But then you will have to cast it back to a non-const char* when passing it to SerialPort():

const char *port_name = "\\\\.\\COM4";
SerialPort arduino(const_cast<char*>(port_name));

或者简单地:

SerialPort arduino(const_cast<char*>("\\\\.\\COM4"));

另一种方法是将port_name声明为非常量char[]缓冲区,将字符串文字复制到其中,然后将其传递给SerialPort():

The alternative is to declare port_name as a non-const char[] buffer, copy the string literal into it, and then pass it to SerialPort():

char port_name[] = "\\\\.\\COM4";
SerialPort arduino(port_name);

这篇关于C2440:"=":无法从"const char [9]"转换为"char *"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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