Declaring readonly variables on a C++ class or struct

前端 未结 3 566
伪装坚强ぢ
伪装坚强ぢ 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:11

    Rather than a collection of constants, you could have a constant collection. The property of being constant seems to pertain to your use case, not the data model itself. Like so:

    struct extent { int width; int height; };
    
    const extent e { 20, 30 };
    

    It's possible to have specifically constant data members of a class, but then you need to write a constructor to initialize it:

    struct Foo
    {
        const int x;
        int & y;
        int z;
    
        Foo(int a, int & b) : x(a + b), y(b), z(b - a) {  }
    };
    

    (The example also shows another type of data member that needs to be initialized: references.)

    Of course, structs and classes are the same thing.

提交回复
热议问题