-->

C2440: '=': cannot convert from 'const

2020-03-30 03:40发布

问题:

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

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?

回答1:

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

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

1: though some C++11 compilers may allow it as a non-standard extension for backwards compatibility, which may need to be enabled manually via compiler flag.

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));

Or simply:

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

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);


回答2:

In C++, in contrast to C, string literals are const. So any pointer to such a string literal must be const, too:

const char* port_name = "\\\\.\\COM4";  // OK
// char* port_name = "\\\\.\\COM4";  // Not OK


标签: c++ arduino qt5