Я хочу хранить экземпляры нескольких классов в векторе. Поскольку все классы наследуются от одного и того же базового класса, это должно быть возможно.
Представьте себе эту программу:
#include <iostream>
#include <vector>
using namespace std;
class Base
{
public:
virtual void identify ()
{
cout << "BASE" << endl;
}
};
class Derived: public Base
{
public:
virtual void identify ()
{
cout << "DERIVED" << endl;
}
};
int main ()
{
Derived derived;
vector<Base> vect;
vect.push_back(derived);
vect[0].identify();
return 0;
}
Я ожидал, что она напечатает «DERIVED», потому что метод «identify» является виртуальным. Вместо этого 'vect [0]' кажется экземпляром 'Base', и он печатает
BASE
Я думаю, я мог бы написать свой собственный контейнер (вероятно, производный от вектора) каким-то образом, способным это делать (возможно, удерживая только указатели ...). Я просто хотел спросить, есть ли для этого еще один метод C ++. И я хотел бы быть полностью векторно-совместимым (просто для удобства, если другие пользователи когда-либо будут использовать мой код).
// Below is the solution by using vector<Based*> vect,
// Base *pBase , and initialized pBase with
// with the address of derived which is
// of type Derived
#include <iostream>
#include <vector>
using namespace std;
class Base
{
public:
virtual void identify ()
{
cout << "BASE" << endl;
}
};
class Derived: public Base
{
public:
virtual void identify ()
{
cout << "DERIVED" << endl;
}
};
int main ()
{
Base *pBase; // The pointer pBase of type " pointer to Base"
Derived derived;
// PBase is initialized with the address of derived which is
// of type Derived
pBase = & derived;
// Store pointer to object of Base class in the vector:
vector<Base*> vect;
// Add an element to vect using pBase which is initialized with the address
// of derived
vect.push_back(pBase);
vect[0]->identify();
return 0;
}