struct Foo {
void setBar(bool bar_) { bar = bar_; }
bool bar;
};
int main() {
Foo f;
f.setBar("true");
}
以上代碼編譯成功由於類型轉換,即使字符數組被傳遞其中bool
預期。如何防止隱式轉換從char數組爲bool
是否有可能導致此代碼編譯失敗? (C++ 03解決方案是首選,因爲我工作場合的編譯器很古老。)
我已經看過以下有關StackOverflow的相關問題,但他們沒有完全解決這個問題。 Preventing implicit conversion in C++,Why does the compiler choose bool over string for implicit typecast of L""?
你是** **不傳遞一個'的std :: string'。你正在傳遞一個'const char [5]'。這會衰變爲一個'const char *',它被轉換爲'bool'。 – juanchopanza
@juanchopanza是的,抱歉,我發現後發佈。我現在已經更新了這個問題。 –