A variable that is read-only after assignment at run-time?

后端 未结 4 1028
小蘑菇
小蘑菇 2021-02-06 05:22

Fairly new programmer here, and an advance apology for silly questions.

I have an int variable in a program that I use to determine what the lengths of my a

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-06 06:07

    C++ doesn't have a built-in solution for this, but if you really want to make sure that your int is only assigned once, you can build your own special int class:

    class MyConstInt
    {
    public: 
        MyConstInt(): assigned(false) {}
        MyConstInt& operator=(int v)
        {
            assert(!assigned); 
            value = v; 
            assigned = true; 
            return *this; 
        }   
        operator int() const 
        { 
            assert(assigned); 
            return value; 
        }
    private: 
        int value; 
        bool assigned; 
    }; 
    
    
    MyConstInt mi; 
    //  int i = mi;         //  assertion failure; mi has no value yet
    mi = 42; 
    //  mi = 43;        //  assertion failure; mi already has a value
    int* array = new int[mi]; 
    

提交回复
热议问题