c++ - 什么时候可以用 const 装饰调用我的重载函数?
问题描述
在下面的代码中,我有两个begin()
功能。什么时候调用第二个 ( const
) 版本?我问的原因是因为STL向量具有相似的特征,但可以正确调用。我希望该行将
abc.begin();
调用const
该函数的版本begin
,但事实并非如此。
#include <vector>
using namespace std;
class test {
public:
test(vector<int> const &x) : a{x} {};
test(vector<int> &x) : b{x} {};
vector<int> begin() {
cout << "int begin() is called" << endl;
return b;
}
const vector<int> begin() const {
cout << "int const begin() const is called" << endl;
return a;
}
private:
const vector<int> a;
vector<int> b;
};
int main() {
vector<int> b{1, 2, 3, 4, 5};
const vector<int> a{4, 5, 6, 7, 8};
test abc{a};
test bcd{b};
bcd.begin();
abc.begin();
return 0;
}
来自 STL 向量的代码示例
iterator begin() _NOEXCEPT {return __make_iter(0);} const_iterator begin() const _NOEXCEPT {return __make_iter(0);}
解决方案
现在我想通了。为了使用 const 成员函数,我们需要将实例声明为常量,即
常量测试 abc{a};
推荐阅读
- python - 使用池调用函数时,它显示未定义主(全局)中的变量
- javascript - 错误属性未定义,但检查未定义
- python - 如何从不同大小的不同文件中进行匹配
- r - 如何从向量中提取特定值?
- python - PyAudio如何找到一定范围的声音频率的音量
- python - 在 Python 中格式化卡到期日期验证器
- windows - AutoHotKey:使 Win+Tab 充当 Alt+Tab,但将所有其他 Win+ 组合重新映射为 Ctrl+
- java - 为什么第一个 if 语句失败?
- c# - 加载资源失败:服务器响应状态为 500 () asp.net mvc
- android - Flutter AndroidX 迁移缺少 android.x 包