Reputation: 13
I'm trying to learn c++ following a book. I've wrote this class definition using std::initializer_list in order to initialize a vector with a list of elements. Vector.h file looks this way:
class Vector
{
public:
Vector(int s);
~Vector();
Vector(std::initializer_list<double>);
void push_back(double);
double& operator[](int i);
int size();
private:
double* elem;
int sz;
};
When I try to compile I have this error message in line 6 (initializer_list one):
error: expected ‘)’ before ‘<’ token
I've also added this code to implement Vector constructor. Vector.cpp looks this way
#include "Vector.h"
#include <stdexcept>
using namespace std;
Vector::Vector(int s)
{
if(s < 0)
{
throw length_error("Vector::operator[]");
}
elem = new double[s];
sz = s;
}
Vector::~Vector()
{
delete[] elem;
}
Vector::Vector(std::initializer_list<double> lst)
{
elem = new double[lst.size()];
sz = static_cast<int>(lst.size());
copy(lst.begin(), lst.end(), elem);
}
double& Vector::operator[](int i)
{
if(i<0 || i>=size())
{
throw out_of_range("Vector::operator[]");
}
return elem[i];
}
int Vector::size()
{
return sz;
}
but compilation also fails with this message:
error: expected constructor, destructor, or type conversion before ‘(’ token
I'm using Code::Blocks width GNU GCC compiler and no extra compiler flags activated. I've tried checking "Have g++ follow the comming C++0x ISO C++ language standard [-std=c++0x]" in Code::Blocks, but errors remain and three new ones raise.
Upvotes: 1
Views: 5532
Reputation: 196
You are missing #include <initializer_list>
also
lst.size()
instead of lst.size
and lst.end()
instead of ls.end()
.
Remember to enable c++11 in compilation.
Upvotes: 2