如何构建一个名字成员在类外可以被修改而在内部是只读的对象

    技术2022-05-19  21

    c++有太多的trick,下面是一个实例,代码如下:

    class Father { public:     Father()         :count(0) {cout << "father create " <<  ++count << " times!" << endl;}         ~Father() {cout << "father destory!" << endl;} protected:     int count; }; class Son : public Father { public:     Son(int i)         : Father(), ival(i)     {cout << "son create " << count << " times" << endl;      cout << ival << endl;}     ~Son()     {         cout << "son destory!" << endl;     } private:     const int& ival; }; int main(int argc, char* argv[]) {     const int iv = 66;         Son son(iv);     son.Son::Son(77);    //将int常量ival的值改为了77     cout << "iv is " << iv << endl;

    }

     

    输出如下:

    father create 1 times! son create 1 times 66 father create 1 times! son create 1 times 77 iv is 66

     

    这段代码通过直接调用类的构造函数的方式使得类的成员变量被初始化了两次,从而绕开了编译器。

    这仅仅是c++的一个技巧,对实际应用没什么帮助,但是可以帮助更好的理解c++。

    如果看不太懂的,请参阅effective c++ 的条款12。

     

    Just for fun!

     

     


    最新回复(0)