C++ 下标运算符重载返回指针并为其赋值

C++ 下标运算符重载返回指针并为其赋值,c++,c++11,pointers,reference,C++,C++11,Pointers,Reference,我遇到了这样一种情况:我有一个类B有一个受保护的数组的a*。我还有一个函数A*func(),它返回指向存储在其他容器中的A对象的指针。(例如std::map或A*arr[]) 例如,以下实现: #include <iostream> using namespace std; class A { public: A(int _x): x(_x){}; int x; }; class B{ public: B() { this->arr[0]

我遇到了这样一种情况:我有一个
B
有一个受保护的
数组
a*
。我还有一个函数
A*func()
,它返回指向存储在其他容器中的
A
对象的指针。(例如
std::map
A*arr[]

例如,以下实现:

#include <iostream>
using namespace std;
class A {
public:
    A(int _x): x(_x){};
    int x;
};
class B{
public:
    B() {
        this->arr[0] = new A(1);
        this->arr[1] = new A(2);
    }
    // use idx to index in to the internal array and return A*
    A*& operator[](int idx); // return reference to pointer to avoid not a lvalue error
private:
    // class B has this private array of A*
    A* arr[2];
};

A*& B::operator[](int idx) {
    return this->arr[idx]; // 0<=idx<=1
}



A* arr[2];
A* func(int x) {
    return arr[x]; // 0<=idx<=1
}

int main() {
    arr[0] = new A(12);
    arr[1] = new A(14);

    B b;

    b[1] = func(1); // assign a new value

    cout << b[1]->x << endl; // prints 14
}
// memory leaks of this program can be removed using `std::shared_ptr<A>` in the place of `A*`.
#包括
使用名称空间std;
甲级{
公众:
A(int_x):x(x){};
int x;
};
B类{
公众:
B(){
此->arr[0]=新A(1);
this->arr[1]=新的A(2);
}
//使用idx索引到内部数组并返回*
*&运算符[](int-idx);//返回对指针的引用以避免出现左值错误
私人:
//类B有一个*
A*arr[2];
};
A*&B::运算符[](int idx){

返回此->arr[idx];//0您还有setter。在应用程序代码中使用原始指针总是充满问题。除非有充分的理由避免使用智能指针,否则请使用智能指针。@Jarod42您的意思是?
b.setValue(idx,func(1))
?是的,我的意思是。如果您的类对指针集合建模,那么我看不出
操作符[]
返回指针引用有任何错误。更一般地说,对
t
类型的元素集合建模的类可以合理地提供
操作符[]
重载返回
T&
;事实上
T
可能恰好是指针类型没有区别。例如,
std::vector::operator[]
实际上会返回
int*&