编写构造函数时,您有机会从其范围之外或其他不希望的情况下测试参数的值。
class a
{
int b;
public:
a(int c)
{
if(c < MIN_ALLOWED || c > MAX_ALLOWED)
{
// Take some mesure
}
else
{
b = c;
}
}
};
但是当您处理const成员时,应该通过初始化列表来对其进行初始化,因此,在这种情况下,如何防止不必要的值?
class a
{
const int b;
public:
a(int c) : b(c)
{
// How to control "c" value?!...
}
};
您可以将变量的验证和修改委派给一个函数。
class a {
public:
a(int c) : b(ValidateAndTransformInputParameter(c)) {}
private:
const int b;
int ValidateAndTransformInputParameter(int d) const {
if (d < 100) {
d = 100;
}
return d;
}
};
执行功能:
class a {
int const b;
public:
a(int const c)
: b { initializeB(c) }
{
}
private:
static int initializeB(int const c)
{
if (c < MIN_ALLOWED || c > MAX_ALLOWED) {
// Take some mesure
return -1; // e,g,
} else {
return c;
}
}
};