我正在尝试根据一本书学习 C++。我使用 std::initializer_list 编写了此类定义,以便使用元素列表初始化 vector 。 Vector.h 文件看起来是这样的:
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;
};
当我尝试编译时,我在第 6 行(initializer_list 之一)中收到此错误消息:
error: expected ‘)’ before ‘<’ token
我还添加了这段代码来实现 Vector 构造函数。 Vector.cpp 看起来是这样的
#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;
}
但编译也失败并显示此消息:
error: expected constructor, destructor, or type conversion before ‘(’ token
我正在使用 Code::Blocks 宽度的 GNU GCC 编译器,并且没有激活额外的编译器标志。我尝试在 Code::Blocks 中检查“让 g++ 遵循即将到来的 C++0x ISO C++ 语言标准 [-std=c++0x]”,但错误仍然存在,并且出现了三个新错误。
最佳答案
你错过了#include <initializer_list>
还
lst.size()
而不是 lst.size
和 lst.end()
而不是 ls.end()
.
记得在编译中启用 c++11。
关于c++ - 错误 : expected ‘)’ before ‘<’ token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27775421/