[英]Wrong constructor is being called
我有一个创建各种变量的类。
并通过一些宏定义,我们想要初始化这些变量。
#define NUMBER(number) JsonVariable(number)
#define STRING(text) JsonVariable(text)
#define TRUE JsonVariable(true)
#define FALSE JsonVariable(false)
数字初始化很好,但是由于未知原因,字符串调用了Bool构造函数。
JsonVariable(string x)
: type(String), s(x)
{
cout << "String" << x << endl;
sleep
}
JsonVariable(bool x)
: type(Boolean), b(x)
{
cout << "Boolean" << x << endl;
sleep
}
如果我注释掉Bool构造函数,则将调用String。
有什么建议么?
编辑:这是具有定义的宏的字符串构造函数。 在构造函数中使用std :: string。
JSON(test) = STRING("Hello")
类型是定义的枚举。 宏也必须用作此分配的一部分。
编辑2:为澄清。 这是枚举类型。
std :: string与命名空间std一起使用,因此与单个字符串一起使用。 另外String来自枚举类型,所以
String != string
typedef enum {
Null, Integer, Double, Boolean, String, Object, Array
} datatype;
您可能会遇到转换规则的影响。 如果传递const char*
,则bool
重载优先于std::string&
:
void f(std::string&) { std::cout << "string"; }
void f(bool) { std::cout << "bool"; }
int main() {
f("abc"); // prints 'bool'
}
这是合乎逻辑的:通常检查指针是否为非零,因此需要转换为int
/ bool
类型。 另一方面,绑定到const std::string&
意味着std::string
构造函数并采用引用。 绑定到std::string&
在这里是不可能的,因为临时对象不会绑定到非const引用。
解决方法是手动创建一个字符串,或者最好是为const char*
提供一个构造const char*
。
根据经验,只要您的API公开了此签名的重载函数或构造函数(或其CV限定和/或引用变体):
void func(std::string){}
void func(bool){}
您应该始终为const char*
提供一个,
void func(std::string){}
void func(bool){}
void func(const char* c){ func(std::string(c)); }
否则,您和您的用户(尤其是)可能会有些微不足道,因为:
字符串字面量 (例如"abc..."
)迅速衰减为const char*
并且通过重载解析,到bool
转换要比std::string
所做的用户定义转换的优先级更高。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.