lundi 7 avril 2014

c ++ - classes abstraites et les pointeurs - Stack Overflow


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.




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>.




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.



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.



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>.



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.


0 commentaires:

Enregistrer un commentaire