【发布时间】:2014-04-16 05:26:22
【问题描述】:
我的代码出现了一个奇怪的问题,编译器似乎将我的参数隐式转换为另一种类型。但是,当我将构造函数标记为显式时,它似乎并没有解决问题。
我的单元测试中有这个
JsonValue stringItem("test");
CHECK(stringItem.type() == JsonValue::Type::String);
结果失败
4 == 3
这些是构造函数的样子...
JsonValue::JsonValue()
: mType(Type::Null) {
}
JsonValue::JsonValue(bool ab)
: mType(Type::Boolean) {
mData.b = ab;
}
JsonValue::JsonValue(int ai)
: mType(Type::Int) {
mData.i = ai;
}
JsonValue::JsonValue(std::uint32_t aui)
: mType(Type::UnsignedInt) {
mData.ui = aui;
}
// It should be using this constructory
// but mType is not getting set to Type::String
JsonValue::JsonValue(const std::string &astr)
: mType(Type::String) {
mData.str = new std::string(astr);
}
正如我之前提到的,将JsonValue(bool) 标记为explicit 并不能解决问题。我还用-Wconversion 编译,没有警告
枚举看起来像这样
enum Type {
Null = 0,
Object,
Array,
String,
Boolean,
Int,
UnsignedInt
};
【问题讨论】:
-
这有点奇怪..您确实在标题中添加了
explicit标签,而不是在构造函数主体中?为了更好的衡量,您可以发布一个完整的程序,以便我们可以原封不动地编译它吗? -
这是一个可运行的版本:ideone.com/qA6Whv
-
我确实使用了一个名为
struct Bool的轻量级包装器bool类型作为我的受歧视工会的成员。
标签: gcc c++11 casting implicit