简体   繁体   English

如何在C ++中赋值之前验证const成员变量的初始化

[英]How to validate the initialization of a const member variable before assigning it in C++

Let's say I have this simple class with a const int member variable: 假设我有一个带有const int成员变量的简单类:

class MyClass{
    public:
        Myclass(int x, int y);
    private:
        const int importantNumber;
        int anotherNumber;
};

MyClass::MyClass(int x, int y) :importantNumber{x}
{
    this->anotherNumber = y;
}

Since int importantNumber is const, I can only set it during the creation of the object by the constructor (with a member initialization list, as seen above). 由于int importantNumber是const,因此我只能在构造函数创建对象的过程中设置它(带有成员初始化列表,如上所示)。

Now, the question: how could I possibly add validation for argument x given to the constructor before actually creating importantNumber with that value? 现在,问题是:在实际使用该值创建重要编号之前,如何在给定值x的构造函数中添加验证? Is it possible to create a static int MyClass::validation(int a) and use it on the member initialization list of the constructor like importantNumber{validation(x)} ? 是否可以创建一个static int MyClass::validation(int a)并将其用于构造函数的成员初始化列表上,例如importantNumber{validation(x)}

Even if it's possible, is there a better way to do it? 即使有可能,还有更好的方法吗?

You just add it. 您只需添加它。

MyClass::MyClass(int x, int y) : importantNumber{validate(x)}
{
    this->anotherNumber = y;
}

The int validate(int original) function can now return something other than x or throw an exception or assert or ask the user for confirmation, whichever you deem appropriate. 现在, int validate(int original)函数可以返回x以外的其他值,或者引发异常, assert或要求用户进行确认,只要您认为合适即可。

If it is just a simple check and you don't want to write a validate function you can use a lambda: 如果这只是简单的检查,而又不想编写validate函数,则可以使用lambda:

MyClass::MyClass(int x, int y) :importantNumber{
    [](int number){
        assert(number > 0);
        return number;
    }(x)}
{
    this->anotherNumber = y;
}

Although this can get a bit convoluted if you overdo it. 尽管如果您这样做过头,这可能会令人费解。

You can use the ternary operator condition ? true : false 您可以使用三元运算符condition ? true : false condition ? true : false in the constructor if you want to validate with a simple condition: condition ? true : false如果要使用简单条件进行验证,则在构造函数中为condition ? true : false

class MyClass{
    public:
        MyClass(int x, int y);
    private:
        const int importantNumber;
        int anotherNumber;
};

MyClass::MyClass(int x, int y) : importantNumber(x > 0 ? x : 0)
{
    this->anotherNumber = y;
}

However, be warned that things can quickly become difficult to read if you overdo it with this operator. 但是,请注意,如果您过度使用此运算符,可能会很快变得难以阅读。

For something more complex, you could do something like this: 对于更复杂的事情,您可以执行以下操作:

int validateIntegral(int x) const
{
    // Do validation on 'x'...

    return x;
}

class MyClass{
    public:
        MyClass(int x, int y);
    private:
        const int importantNumber;
        int anotherNumber;
};

MyClass::MyClass(int x, int y) : importantNumber(validateIntegral(x))
{
    this->anotherNumber = y;
}

Use factory function for creating a class instead of constructor. 使用工厂函数创建类而不是构造函数。

class MyClass
{
public:
  static MyClass* create (int x, int y);

private:
  MyClass(int x, int y);

private:
  const int importantNumber;
  int anotherNumber;
};

MyClass* MyClass::create (int x, int y)
{
  return x > 0 ? new MyClass(x, y) : NULL;
}

When you need some advanced validation of parameters, factories have following advantages: 当您需要对参数进行一些高级验证时,工厂具有以下优点:

  • They avoid creation of object in memory if tests fail 如果测试失败,它们可以避免在内存中创建对象
  • They have more flexibility over checking parameters in initialization list 与检查初始化列表中的参数相比,它们具有更大的灵活性
  • You can return NULL if you dont need exceptions nor you want to have some ".is_valid()" member function for your class. 如果您不需要异常,或者您不想为类使用某些“ .is_valid()”成员函数,则可以返回NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 const * const *成员变量初始化c ++ - const * const * member variable initialization c++ C ++ const静态成员数组初始化 - C++ const static member array initialization C ++静态const模板成员初始化 - C++ static const template member initialization C ++如果值来自成员变量,则复制​​初始化和const引用初始化之间存在差异 - C++ Difference between copy initialization and const reference initialization if value comes from member variable 数组初始化在C++中使用const变量 - Array initialization use const variable in C++ 为什么在C ++中不允许初始化整数成员变量(不是const static)? - Why is initialization of integer member variable (which is not const static) not allowed in C++? 从C ++的构造函数中向成员const char *变量分配字符串文字时会发生什么? - What happens when assigning a string literal to a member const char* variable from within a constructor in C++? 在C ++中将指针变量分配给const int? - Assigning a pointer variable to a const int in C++? 在没有初始化列表的情况下将值分配给C ++中头文件中的const int - Assigning values to const int in headerfile in c++ without initialization list 如何在C ++的子类构造函数中初始化超类的const成员变量? - How to initialise const member variable of superclass in constructor of subclass in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM