struct Foo {
void setBar(bool bar_) { bar = bar_; }
bool bar;
};
int main() {
Foo f;
f.setBar("true");
}
由于类型转换,上述代码编译成功,即使在需要 bool
的地方传递了一个 char 数组。
是否有可能导致这段代码编译失败? (首选 C++03 解决方案,因为我工作场所的编译器很古老。)
我查看了 StackOverflow 上的以下相关问题,但它们并没有完全解决这个问题。 Preventing implicit conversion in C++ , Why does the compiler choose bool over string for implicit typecast of L""?
最佳答案
您可以声明一个采用const char*
并且不提供定义的函数:
void setBar(const char*);
这将使它在链接时失败。不过,您仍然需要进行所有其他隐式转换 - 从任何指针到 bool、整数到 bool、 float 到 bool ...
另一种选择:
struct Foo {
void setBar(bool bar_) {}
private:
template<typename T>
void setBar(T bar) {}
};
这样,如果您使用 bool
以外的任何其他方式调用它,您将收到关于它是私有(private)的错误。
关于c++ - 如何防止从 char 数组到 bool 的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18463937/