重载operator []以替换向量元素 [英] Overload operator [] to replace vector elements
问题描述
我有一个 classA ,其中包含向量< classB *> vObject 。
class ClassA {
public:
ClassB ** operator [](int index);
private:
vector< ClassB *> vObject
};
让我们假设vObject填充了一些classB *对象。
我想要做的是能够替换矢量的classB *元素:
classA_obj [3] = classA_obj [5];
classA_obj [1] = classB_obj;
我试图返回一个ClassB Element的指针。
这是我当前的操作符实现:
ClassB ** ClassA :: operator [](int index){
return& vObject [index]; }
之后,我尝试了以下操作:
* classA_obj [3] = * classA_obj [5]
使用向量完成所有工作的代码是:
向量< ClassB *> vObject;
vObject.push_back(new ClassB(ARG1,ARG2));
vObject.push_back(new ClassB(ARG1,ARG2));
vObject [0] = vObject [1];
我真的很困惑,我认为我的代码是正确的,但它实际上不工作。
上面的代码只是我实际代码的一个例子。 / p>
如果您返回参考,您将能够替换您要求的内容。
class ClassA {
对象而不是指针。
public:
ClassB *& operator [](int index){return vObject [index]; }
private:
std :: vector< ClassB *> vObject
};但是,你描述你的用法的方式似乎表明你可以很容易地改变你的矢量持有 code> ClassBclass ClassA {
public :
ClassB& operator [](int index){return vObject [index]; }
private:
std :: vector< ClassB> vObject
};
然后代替将
new ClassB
向量,你只需按ClassB
:vObject.push_back ARG1,ARG2));
vObject.push_back(ClassB(ARG1,ARG2));
这有你不需要显式访问你的容器删除指针的优势。否则,您需要更新
ClassA
才能服从第三条规则。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.
解决方案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 pushClassB
: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.这篇关于重载operator []以替换向量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!