我正在将 java 程序转换为 C++,该架构要求我在某些点返回空指针。 我有一个这样构造的指针:
auto p= std::make_unique< std::array< A, 3>>();
其中 A 的形式为:
class A
{
public:
double x = 0, y = 0;
A(const double x, const double y):
x(x), y(y)
{}
};
现在,我需要通过指针设置成员,所以我想:
p[0].x += 1.0;
自 unique_ptr
具有解除引用 []
运算符,但失败并显示:
error: no match for 'operator[]' (operand types are 'std::unique_ptr<std::array<A, 3ull> >' and 'int')
我回顾了类似的问题,但我不清楚我想做的事情是否可行。是[]
运算符仅适用于 C 风格声明的数组?
最佳答案
Is the
[]
operator for c-style declared arrays only?
是的,仅支持阵列版本,即 unique_ptr<T[]>
, std::array
不计算在内。
您可以使用operator*
相反,就像
(*p)[0].x += 1.0;
关于c++ - std::array :通过智能指针访问元素的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43905221/