C/C++ changing the value of a const

后端 未结 18 1841
醉梦人生
醉梦人生 2020-11-28 07:28

I had an article, but I lost it. It showed and described a couple of C/C++ tricks that people should be careful. One of them interested me but now that I am trying to repli

18条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 07:58

    I have tested the code below and it successfully changes the constant member variables.

    #include 
    
    class A
    {
        private:
            int * pc1;  // These must stay on the top of the constant member variables.
            int * pc2;  // Because, they must be initialized first
            int * pc3;  // in the constructor initialization list.
        public:
            A() : c1(0), c2(0), c3(0), v1(0), v2(0), v3(0) {}
            A(const A & other)
                :   pc1 (const_cast(&other.c1)),
                    pc2 (const_cast(&other.c2)),
                    pc3 (const_cast(&other.c3)),
                    c1  (*pc1),
                    c2  (*pc2),
                    c3  (*pc3),
                    v1  (other.v1),
                    v2  (other.v2),
                    v3  (other.v3)
            {
            }
            A(int c11, int c22, int c33, int v11, int v22, int v33) : c1(c11), c2(c22), c3(c33), v1(v11), v2(v22), v3(v33)
            {
            }
            const A & operator=(const A & Rhs)
            {
                pc1     =  const_cast(&c1);
                pc2     =  const_cast(&c2),
                pc3     =  const_cast(&c3),
                *pc1    = *const_cast(&Rhs.c1);
                *pc2    = *const_cast(&Rhs.c2);
                *pc3    = *const_cast(&Rhs.c3);
                v1      = Rhs.v1;
                v2      = Rhs.v2;
                v3      = Rhs.v3;
                return *this;
            }
            const int c1;
            const int c2;
            const int c3;
            int v1;
            int v2;
            int v3;
    };
    
    std::wostream & operator<<(std::wostream & os, const A & a)
    {
        os << a.c1 << '\t' << a.c2 << '\t' << a.c3 << '\t' << a.v1 << '\t' << a.v2 << '\t' << a.v3 << std::endl;
        return os;
    }
    
    int wmain(int argc, wchar_t *argv[], wchar_t *envp[])
    {
        A ObjA(10, 20, 30, 11, 22, 33);
        A ObjB(40, 50, 60, 44, 55, 66);
        A ObjC(70, 80, 90, 77, 88, 99);
        A ObjD(ObjA);
        ObjB = ObjC;
        std::wcout << ObjA << ObjB << ObjC << ObjD;
    
        system("pause");
        return 0;
    }
    

    The console output is:

    10      20      30      11      22      33
    70      80      90      77      88      99
    70      80      90      77      88      99
    10      20      30      11      22      33
    Press any key to continue . . .
    

    Here, the handicap is, you have to define as many pointers as number of constant member variables you have.

提交回复
热议问题