简体   繁体   中英

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

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM