Hi,
I was trying to use inheritance to make the existing std::vector to a two dimensional vector.Here is the code below.
#include "stdafx.h"
#include<vector>
#include<iostream>
using namespace std;
//TwoDVector.h
class TwoDVector:public vector<char>
{
public:
TwoDVector(int x,int y);
const int xDimension;
const int yDimension;
vector<char> TwoD;
char get(int x,int y);
void put(int x,int y,char c);
};
//TwoDVector.cpp
#include "stdafx.h"
#include<vector>
#include "TwoDVector.h"
#include<iostream>
using namespace std;
But I am getting the following errors.Please Could someone help?
1>Compiling...
1>TwoDVector.cpp
1>.\TwoDVector.cpp(10) : error C2614: 'TwoDVector' : illegal member initialization: 'twoD' is not a base or member
1>.\TwoDVector.cpp(13) : error C2065: 'twoD' : undeclared identifier
1>.\TwoDVector.cpp(19) : error C2065: 'twoD' : undeclared identifier
1>.\TwoDVector.cpp(24) : error C2065: 'twoD' : undeclared identifier
Since none of vector's members are virutal (not even its destructor), you're better off not derviing from vector. You could probably hack together something that works, but it would be a lot of effort and would undoubtedly behave strangely if used a certain way (I've tried deriving from STL classes before -- it's not fun or easy).
Instead, you can make your own class which 'has-a' vector, and simply interfaces outside of it.
1 2 3 4 5 6 7 8
class vector2d
{
public:
// get/set stuff here
protected:
vector<int> thevectortouse;
};
Of course instead of using int like I do here (and like you did in your example), you could make this a template class:
1 2 3 4 5 6
template <typename T>
class vector2d
{
//...
vector<T> thevectortouse;
};
What makes you think std::vector can or should be subclassed? (Hint: Containers are not designed to be subclassed. You can tell by the lack of a virtual destructor.)
typedef std::vector<std::vector> 2dVector;
And then create a factory function to make constructing them easier.