![](/img/trans.png)
[英]Using C++ with Objective-C, How can I fix “Conflicting declaration 'typedef int BOOL'”?
[英]How can I fix an int-to-bool warning in C++?
當我嘗試從文件中讀取一個整數並使bool變量等於它時,我在MSVC ++中收到警告。
accessLV[i] = FileRead(file1, i + 1);
(accessLV是一個bool數組,FileRead是我為減少從文件讀取所涉及的語法而做的一個函數,我是因為該語句在for循環中)
我嘗試過使用static_cast:
accessLV[i] = static_cast<bool>(FileRead(file1, i + 1));
但我仍然得到警告。 我試過這樣做(我不確定確切的術語):
accessLV[i] = (bool)FileRead(file1, i + 1));
警告仍在那里。 反正有沒有使accessVV成為一個整數的數組擺脫警告?
注意:這是FileRead的語法,如果它有幫助:
int FileRead(std::fstream& file, int pos)
{
int data;
file.seekg(file.beg + pos * sizeof(int));
file.read(reinterpret_cast<char*>(&data), sizeof(data));
return data;
}
怎么樣
accessLV[i] = FileRead(file1, i + 1) != 0;
你想要做的基本上是
accessLV [i] =(FileRead(file1,i + 1)!= 0)
accessLV[i] = FileRead(file1, i + 1) != 0;
在上面,你是從int轉換為bool:如果你使用它,比較的結果放在accessLV [i]中,所以不會出現類型警告。
正如其他海報所說, !=0
就是你所需要的。 我更喜歡這樣的包裝器,因為我覺得它更具可讀性:
// myutil.hpp
template< typename T >
inline bool bool_cast( const T & t ) { return t != 0; }
在這種情況下你會使用這樣的:
// yourcode.cpp
accessLV[ i ] = bool_cast( FileRead( file1, i + 1 ) );
這個相關問題還有一些您可能會覺得有用的討論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.