Abstract classes and Pointers

廉价感情. 提交于 2019-12-24 09:59:30

问题


I have a class

// i want an abstract class.

class Foo
{
    public:
    virtual void bar()=0;
};

// i want this abstract calss to be used all over the program :) to enjoy polymorphism.

class EatFoo
{
public:
    vector<Foo> fooV; // not working
    vector<Foo *> fooPV;
};

I get a compile time error that abstract class cannot be instantiated.

Yes its true but i really want or i want to learn :

how to make other programmers "have to - have to" implement some function and i donot want to use pointers in my programs. [i donot know why ? but i have that gut feeling..]

Is there some pattern or something that can help me. With java it is all references and yup it is doable.

Thanks.


回答1:


If you want polymorphic behaviour for container items, you have no choice but to use pointers. To make your life as easy as possible, you should use smart pointers, such as shared_ptr<Foo>.




回答2:


Your gut is right... partly...

You shouldn't use raw pointers:

class EatFoo
{
public:
    vector<shared_ptr<Foo> > fooV;
};

There's no way in C++ to have collections of abstract objects.



来源:https://stackoverflow.com/questions/13904406/abstract-classes-and-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!