一个简单的问题,我想很容易回答这个问题(如果我自己还没有得到的话)。以下重载函数:
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;
^~
[我猜我遇到问题是因为类型bool
和int
相同(true => int(1), false => int(0)
。当我将吸气剂名称更改为例如bool getBR(const int reactionNumber) {...}
时,一切正常。所以我想问题是关于c ++中bool
和int
处理的相似性。我也尝试了各种不同的调用,例如:
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(...)
因此,我认为它确实与bool
和int
重载参数有关。但是,我进行了快速搜索,但对这两种重载类型以及由此产生的问题并没有发现太多。 Tobi
这是因为您声明BR(int)
而不是BR(bool)
为const
。然后,当您在非const对象上调用BR(int)
时,编译器具有两个相互冲突的匹配规则:参数匹配有利于BR(int)
,但是const
-ness匹配有利于BR(bool)
。