C2440:“=":无法从“const char [9]"转换为“char*" [英] C2440: '=': cannot convert from 'const char [9]' to '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*'
指向下面的代码行:
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 *
或 charconst *
).但是,在将它传递给 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屋!