浅谈const变量赋值报错分析

2020-01-06 13:08:07王振洲

看以下示例:
 

  1. class Foo {  public: 
  2.  Foo(){     i = 1; 
  3.  }   void modify(){// make some modification to the this object 
  4.    i = 2;   }  
  5.  void print() const {     cout << "Foo_i:" << i << endl; 
  6.  }  private: 
  7.  int i;  }; 
  8.   //演示潜在的危险   
  9. //error: invalid conversion from `Foo**' to `const Foo**'  ///////////////////////////////////////////////////////// 
  10. int main(int argc, char *argv[])  { 
  11.   const Foo x;    Foo* p; 
  12.     //const Foo ** q = &p; //q now points to p; this is (fortunately!) an error 
  13.   const Foo ** q = const_cast<const Foo **>(&p);     *q = &x; // p now points to x 
  14.   p->modify(); // Ouch: modifies a const Foo!!     x.print(); // print: Foo_i:2 
  15.   return 0;  } 
?

我们定义了一个常量的Foo,常量Foo方法打印出来的永远为1; 

Foo**到const Foo **的转换报错, 

通过一个强转符让编译通过, 

最后的x.print()的结果是2;这样的潜在危险在正式的项目代码中就很难发现; 

很难会想到一个const对象还能够变更;

以上所述就是本文的全部内容了,希望大家能够喜欢。