Pun*_*oni 4 c++ validation constructor c++11
以下示例显示了问题的症结所在.我需要初始化类的const成员.这只能在初始化列表中完成,而不能在构造函数体中完成.如果构造函数的输入无效,也就是说,如果向量大小小于3,我想断言或抛出错误.
class A {
// In following constructor, how do we make sure if params.size()
// is at least 3.
A(const std::vector<int>& params):
x(params[0]), y(params[1]), z(params[2]) {}
private:
const int x;
const int y;
const int z;
};
Run Code Online (Sandbox Code Playgroud)
请告知如何在Modern C++(11及更高版本)中实现这一目标
只需添加一个抽象层.您可以编写一个函数来确保向量的大小正确,甚至可以确保值在预期的范围内(如果有的话).那看起来像
class A {
A(const std::vector<int>& params):
x(verify(params, 0)), y(verify(params, 1)), z(verify(params, 3)) {}
private:
static int verify(const std::vector<int>& params, int index)
{
if (params.size() < 4) // or use if (params.size() <= index) if you only care if the index will work
throw something;
return params[index];
}
const int x;
const int y;
const int z;
};
Run Code Online (Sandbox Code Playgroud)
const
成员只能在构造函数的成员初始化列表中初始化。要验证调用者的输入,您必须调用辅助函数来验证每个输入值,然后再将其传递给相应的成员,例如:
int check(const std::vector<int> ¶ms, int index) {
if (params.size() <= index) throw std::length_error("");
return params[index];
}
class A {
A(const std::vector<int>& params):
x(check(params, 0)), y(check(params, 1)), z(check(params, 3)) {}
private:
const int x;
const int y;
const int z;
};
Run Code Online (Sandbox Code Playgroud)
或者,只需使用vector
自己的内置边界检查即可:
class A {
A(const std::vector<int>& params):
x(params.at(0)), y(params.at(1)), z(params.at(3)) {}
private:
const int x;
const int y;
const int z;
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1146 次 |
最近记录: |