gpt4 book ai didi

c++ - C++重载函数,包括bool和整数参数

转载 作者:行者123 更新时间:2023-12-02 10:53:12 25 4
gpt4 key购买 nike

一个简单且我想容易回答的问题(如果我自己还没有得到的话)。以下重载函数:

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)。当我将 setter/getter 名称更改为 bool getBR(const int reactionNumber) {...}时,一切正常,所以我想问题出在 boolint的相似之处在c++中进行处理。我也尝试了各种不同的调用,例如:
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。然后,当您在非const对象上调用BR(int)时,编译器具有两个冲突的匹配规则:参数匹配有利于BR(int),但是const -ness匹配有利于BR(bool)

关于c++ - C++重载函数,包括bool和整数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60681839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com