Declaring readonly variables on a C++ class or struct

前端 未结 3 540
伪装坚强ぢ
伪装坚强ぢ 2021-01-05 07:39

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;
            


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 08:09

    There is a const modifier:

    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;
       };
    

提交回复
热议问题