开发者

C++ Problem with polymorphed methods in vector of pointers

开发者 https://www.devze.com 2023-02-23 00:59 出处:网络
first and foremost sorry for my bad english, I\'m no english native =/ I have a vector of pointers directing at my base class A which is filled by classes B and C.

first and foremost sorry for my bad english, I'm no english native =/

I have a vector of pointers directing at my base class A which is filled by classes B and C. B and C are polymorphic classes from A, which have only one more method, setTest(). Now I want to call a method from B/C through the vector:

vector (A*) vec;
vec.push_back(new classB());
vec.push_back(new classC());

for(int i=0;i<3;++i)
    vec[i]->setTest(true);

But the compiler 开发者_如何学编程says there is no method setTest() in my baseclass A. Any ideas how I can fix this?


Since compiler "think" that deals with A, it cannot deduce that method setTest exists.

To resolve this problem you can do following:

Add abstract method to A:

 virtual void setTest(bool value) = 0;

Update

There is another way. Let's create helper interface D with only one method:

 struct D
 {
     virtual void setTest(bool value) = 0;
 };

Than using multiple inheritance change signature of B and C:

class B : public A, public D
{
     virtual void setTest(bool value)
     {
         //your impl goes here...
     }
};

//do the same with impl of C

And at last let's change iteration:

for(int i=0;i<3;++i)
    ((D*)vec[i])->setTest(true);

Simple casting allows call expected method. BUT!!! if vector can contains instances of A than it will fail, so using dynamic_cast helps:

for(int i=0;i<3;++i)
{
     D *check_inst = dynamic_cast<D*>(vec[i]);
     if( check_inst)
        check_inst->setTest(true);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消