I have two classes, derived from a common class. The common class has a pure virtual function called execute(), which is implemented in both derived classes. In the inherited class I have an attribute which is a vector. In both execute() methods I overwrite this vector with a result. I access both classes from a vector of pointers to their objects. The problem is when I try to access the result vector form outside the objects. In one case I can get the elements (which are simply pointers), in the other I cannot, the vector is empty.
Code:
class E;
class A{
protected:
vector<E*> _result;
public:
virtual void execute()=0;
vector<E*> get_result();
};
vector<E*> A::get_result()
{
return _result;
}
class B : public A
{
public:
virtual void execute();
};
B::execute()
{
//...
_result = tempVec;
return;
}
class C : public A
{
public:
virtual void execute();
};
C::execute()
{
//different stuff to B
_result = tempvec;
return;
}
main()
{
B* b = new B();
C* c = new C();
b->execute();
c->execute();
b->get_result();//returns full vector
c->get_result(); //returns empty vector!!
}
I have no idea what is going on here... I have tried fill开发者_JS百科ing _result by hand from a temp vector in the offending class, doing the same with vector::assign(), nothing works. And the other object works perfectly. I must be missing something.... Any help would be greatly appreciated.
Since everything else is the same between classes B
and C
I would have to say that the line
//different stuff to B
is probably important!
Also your get_result()
method should really be
const vector<E*>& get_result() const;
to save you making a copy of the vector each time.
I was wondering where that tempVec was coming from but after Troubadour's response I realized that you were omitting code. There's got to be a problem there as I don't see anything going wrong with the code at this point.
I think I know what the matter. In class B ::execute method is saving tempVec, (V - is big), in class C it is saving tempvec. well, tempVec - is not empty, tempvec - is empty. Don't see anything wrong.
精彩评论