【问题标题】:std::array : access member of element through smart pointerstd::array : 通过智能指针访问元素的成员
【发布时间】:2017-05-11 01:50:23
【问题描述】:

我正在将一个 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 样式声明的数组?

【问题讨论】:

    标签: c++ arrays c++11 pointers syntax


    【解决方案1】:

    [] 运算符是否仅用于 c 样式声明的数组?

    是的,仅支持数组版本,即unique_ptr<T[]>,std::array 不计算在内。

    你可以改用operator*,比如

    (*p)[0].x += 1.0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2019-01-17
      相关资源
      最近更新 更多