更新时间:2023-02-03 08:47:08
这个问题来自构造函数中的隐式转换。 字符串字面值(如代码中的字符串字面值)存储为 const char 类型。因为你没有一个采用这种类型的构造函数,编译器会尝试找到一个可以在你的构造函数中找到的类型的转换。
在这种情况下 const char *
转换为 bool
更容易 QString
do:
DB_Variable foo(some_name,);
构造函数
DB_Variable(QString name,bool newValue):
请注意,你看到的行为不是因为得到不同于任何其他字符串字面量,它只是你很可能没有一个类型
bool,bool
的构造函数(你的所有构造函数都取一个 QString
第一个参数?)。几率是如果你有一个构造函数如下:
DB_Variable(bool test1,bool newValue):
然后,当您执行 DB_Variable foo(some_name );
要获得想要的结果,您可以传入 QStrings
像这样:
DB_Variable foo(QString(some_name),QString());
或者定义一个构造函数 const char *
代表第二个参数。
Im am working on a QT project and have found a strange behaviour:
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){}
I now want to use the first constructor to create an object like this:
DB_Variable foo("some_name"," ");
I'd expect the empty string to be interpreted as a QString, but the second (bool) constructor is called. Can someone tell my why? Is the " " a pointer to an empty string and the then somehow rather a bool than a string?
Foo
This problem results from implicit conversions going on in the constructor. String literals, such as the one in your code, are stored as const char
types. Because you didn't have a constructor taking this type the compiler tries to find the conversion to a type that it can find in one of your constructors.
In this case const char*
converts to bool
easier that QString
so when you do:
DB_Variable foo("some_name"," ");
The constructor
DB_Variable(QString name, bool newValue):
Is called.
Note that the behavior you are seeing isn't due to " "
getting treated differently than any other string literal, it's just that you most likely didn't have a constructor with the types bool, bool
(did all your constructors take a QString
as the first argument?). Chances are if you had a constructor such as the following:
DB_Variable(bool test1, bool newValue):
Then this would have been called instead when you did something such as DB_Variable foo("some_name"," ");
To get the results you wanted you could pass in QStrings
like so:
DB_Variable foo(QString("some_name"), QString());
Or perhaps define a constructor that takes const char*
for the second parameter.