Am trying to inherit a class from a C++ vector and initialize it at the constructor. How do I do it? For example:
class Dataset:public std::vector<float>{
public:
Dataset(vector<float> val):*baseclass*(va开发者_高级运维l){}
// bruteforce way. // Dataset(vector<float> val){//for every val[i] call push_back(val[i]);}
ofcourse there's nothing as baseclass, what I mean by the above statement is I want to initialize the vector's data with val. how do I do it without push_back ing every element?
Don't derive from std::vector<>
. This class was never meant to be derived from. Use an instance of the class as a member instead:
struct Owns {
Owns() : the_vector_(42, 128) { }
private:
std::vector<float> the_vector_;
};
You could write :
Dataset(const vector<float> &val): std::vector<float>(val) {}
but in the end, you really shouldn't inherit publicly from std::vector
. There are multiple hints which show that std::vector
is just not meant to be derived :
- No virtual destructor
- No protected members
- No virtual functions
You can't prevent anyone from treating your Dataset
object as a std::vector<float>
, because public inheritance means that Dataset
is a std::vector<float>
, and this will fail miserably if someone attempts to delete a Database
object through a std::vector<float>
pointer.
If you want to reuse std::vector
, either use a private std::vector
member, or inherit privately and expose what should be through using
declarations.
精彩评论