An empty string is interpreted as a bool in the Constructor

I am working on a QT project and have discovered strange behavior:

I have a class with several constructors that look like

DB_Variable(QString name, QString newValue):
name(name),value_string(newValue), var_type(DB_STRING){}

DB_Variable(QString name, bool newValue):
    name(name), value_bool(newValue), var_type(DB_BOOL){}

Now I want to use the first constructor to create such an object:

DB_Variable foo("some_name"," ");

I expect the empty string to be interpreted as a QString, but the second (bool) constructor is called. Can someone tell me why? Is "" a pointer to an empty string, and then somehow more likely to bool than to a string?

Foo

+4
source share
3 answers

- , . , , const char . , , , .

const char* bool, QString, :

DB_Variable foo("some_name"," ");

DB_Variable(QString name, bool newValue):

.

, , , , " " , , , , , bool, bool ( a QString ?). , , :

DB_Variable(bool test1, bool newValue):

, - DB_Variable foo("some_name"," ");

, QStrings :

DB_Variable foo(QString("some_name"), QString());

, , , const char* .

+6

" " - char*. bool, QString.

+1

, QString, (bool) . - ?

" " char[2] char*, int, int bool.

I am not very familiar with Qt, but if the constructor for QString(which takes the char [N] or char * parameter), then it will only use the first constructor when you write

DB_Variable foo("some_name", QString{ " " });
                   // HERE:  ^^^^^^^^     ^

The easiest solution is to add a third constructor to your DB_Variable class. You can do this in several ways, but if you want the null value to be (by default) set to " ", you should write code similar to this:

DB_Variable(QString name):
name(name),value_string(" "), var_type(DB_STRING){}

Client Code:

DB_Variable foo("some_name"); // create variable with empty value (actually " " value)
+1
source

Source: https://habr.com/ru/post/1546000/


All Articles