在 C++ 类或结构上声明只读变量

2022-01-24 00:00:00 constants struct c++

我从 C# 开始使用 C++,而 const 正确性对我来说仍然是新事物.在 C# 中,我可以声明这样的属性:

I'm coming to C++ from C# and const-correctness is still new to me. In C# I could declare a property like this:

class Type 
{
    public readonly int x;
    public Type(int y) 
    {
        x = y;
    }
}

这将确保 x 仅在初始化期间设置.我想在 C++ 中做类似的事情.我能想到的最好的方法是:

This would ensure that x was only set during initialization. I would like to do something similar in C++. The best I can come up with though is:

class Type
{
private:
    int _x;
public:
    Type(int y) { _x = y; }
    int get_x() { return _x; }
};

有没有更好的方法来做到这一点?更好的是:我可以用结构来做到这一点吗?我想到的类型实际上只是一个数据集合,没有逻辑,所以如果我能保证它的值只在初始化期间设置,结构会更好.

Is there a better way to do this? Even better: Can I do this with a struct? The type I have in mind is really just a collection of data, with no logic, so a struct would be better if I could guarantee that its values are set only during initialization.

推荐答案

有一个 const 修饰符:

class Type
{
private:
   const int _x;
   int j;

public:
    Type(int y):_x(y) { j = 5; }
    int get_x() { return _x; }
    // disable changing the object through assignment
    Type& operator=(const Type&) = delete;
};

请注意,您需要在构造函数初始化列表中初始化常量.其他变量你也可以在构造函数体中初始化.

Note that you need to initialize constant in the constructor initialization list. Other variables you can also initialize in the constructor body.

关于你的第二个问题,是的,你可以这样做:

About your second question, yes, you can do something like this:

   struct Type
   {
      const int x; 
      const int y;

      Type(int vx, int vy): x(vx), y(vy){}
      // disable changing the object through assignment
      Type& operator=(const Type&) = delete;
   };

相关文章