Vic*_*tor 4 c++ operator-overloading stdarray
我想优化我的代码重载std :: array中的bracket []运算符,我在任何地方都减去一个.代码编译但从不调用重载函数,任何人都可以告诉我为什么?
#include <iostream>
#include <array>
class A
{
std::array<int,5> var{0, 1, 2, 3, 4};
std::array<int, 5ul>::value_type& operator[](std::size_t p_index);
};
std::array<int, 5ul>::value_type& A::operator[](std::size_t p_index)
{
return var[p_index - 1];
}
int main()
{
A a;
std::cout << a.var[1] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
代码返回"1"但我希望"0".提前致谢!
您不是[]为您的阵列"重载"订阅运算符; 您宁愿为类定义自己的订阅运算符A,它将在AA的数据成员的实例上调用,而不是在其实例上调用var.
所以你需要写...
std::cout << a[1] << std::endl;
Run Code Online (Sandbox Code Playgroud)
输出:
0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |