簡體   English   中英

C++ 重載函數,包括 bool 和 integer 參數

[英]c++ overloading function including bool and integer arguments

一個簡單的,我想很容易回答的問題(如果我自己還沒有得到的話)。 以下重載函數:

void BR(const bool set) { backwardReaction_[nReac_] = set; }
bool BR(const int reactionNumber) const { return backwardReaction_[reactionNumber]; }

第一個函數是 setter 函數,第二個函數是 getter 函數。 backwardReaction_ _的類型為std::vector<bool> 每當我想調用第二個函數時就會出現問題。 在這里我得到一個編譯器錯誤overload function BR(xy) ambigious

int main()
.
.
const int i = 3;
bool a = chem.BR(i);

編譯器錯誤等於:

chemistryTestProg.cpp: In function ‘int main()’:
chemistryTestProg.cpp:74:34: error: call of overloaded ‘BR(const int&)’ is ambiguous
     const bool a = chem.BR(i);
                             ^
In file included from ../../src/gcc/lnInclude/chemistryCalc.hpp:38:0,
                 from ../../src/gcc/lnInclude/chemistry.hpp:38,
                 from chemistryTestProg.cpp:35:
../../src/gcc/lnInclude/chemistryData.hpp:266:18: note: candidate: void AFC::ChemistryData::BR(bool)
             void BR(const bool);
                  ^~
../../src/gcc/lnInclude/chemistryData.hpp:322:22: note: candidate: bool AFC::ChemistryData::BR(int) const
                 bool BR(const int) const;
                      ^~

我想我遇到問題是因為boolint類型相同( true => int(1), false => int(0) 。因為我正在將 getter 名稱更改為,例如bool getBR(const int reactionNumber) {...}一切正常。所以我想問題在於 c++ 中boolint處理的相似性。我還嘗試了各種不同的調用,例如:

const bool a = chem.BR(4)
const bool a = chem.BR(int(5))
const bool a = chem.BR(static_cast<const int>(2))
bool a = chem.BR(...)

因此,我認為它確實與boolint重載參數有關。 盡管如此,我進行了快速搜索,並沒有找到太多關於這兩種重載類型和由此產生的問題。 托比

這是因為您將BR(int)而不是BR(bool)const 然后當你在一個非常量對象上調用BR(int)時,編譯器有兩個相互沖突的匹配規則:參數匹配有利於BR(int) ,但const匹配有利於BR(bool)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM