Overload operator [] to replace vector elements

2019-07-30 13:22发布

问题:

I have a classA which has a vector< classB* > vObject.

class ClassA{
public:
     ClassB** operator [] (int index);
private:
     vector<ClassB*> vObject
};

Let's Assume that vObject is filled with some classB* objects. What I want to do is to be able to replace classB* elements of vector like that:

classA_obj[3] = classA_obj[5];
classA_obj[1] = classB_obj;

I tried to return a pointer of ClassB Element. Here is my current operator implementation:

ClassB** ClassA::operator [](int index){
    return &vObject[index]; }

After that i tried the following:

*classA_obj[3] = *classA_obj[5]

The code of doing all the work with just a vector would be:

vector<ClassB*> vObject;
vObject.push_back(new ClassB(ARG1,ARG2));
vObject.push_back(new ClassB(ARG1,ARG2));
vObject[0] = vObject[1];

I'm really confused about this, I thought my code was right but it actually doesn't work. I would love if someone could tell me what I'm doing wrong.

The above code is just a sample of my actual code.

回答1:

If you return a reference, you will be able to do the replacement you requested.

class ClassA{
public:
     ClassB*& operator [] (int index) { return vObject[index]; }
private:
     std::vector<ClassB*> vObject
};

However, the way you have described your usage seems to indicate you can easily change your vector to hold ClassB objects instead of pointers.

class ClassA{
public:
     ClassB& operator [] (int index) { return vObject[index]; }
private:
     std::vector<ClassB> vObject
};

Then instead of pushing new ClassB into the vector, you just push ClassB:

vObject.push_back(ClassB(ARG1,ARG2));
vObject.push_back(ClassB(ARG1,ARG2));

This has the advantage you not needing to explicitly visit your container to delete the pointers. Otherwise, you will need to update ClassA to obey the rule of three.



回答2:

The ordinary std::vector returns a reference, so you should probably try that:

ClassB*& ClassA::operator [](int index)
{
     return vObject[index]; 
} 


回答3:

In the definition:
class A {
  public:
          ClassB*& operator [] (int index) { return vObject.at(index); };
  private:
          vector<ClassB*> vObject;
}

It's a inline function, nothing else to be done. However, I would check index just for sanity.