Declaring readonly variables on a C++ class or struct

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

    You can initialize class const members with constructor. If you need add some other logic in constructor, but in .cpp file not in .h, you can create a private method and call it in constructor.

    File.h

        class Example 
        {
        private:
            const int constantMember1;
            const int constantMember2;
            const int constantMember3;
            void Init();
        public:
            Example(int a, int b) :constantMember1(a), constantMember2(b), constantMember3(a + b) {
               //Initialization
               Init();
            };
        };
    

    File.cpp

    void Init()
    {
    //Some Logic intialization
    }
    

提交回复
热议问题