看以下示例:
?
- class Foo { public:
- Foo(){ i = 1;
- } void modify(){// make some modification to the this object
- i = 2; }
- void print() const { cout << "Foo_i:" << i << endl;
- } private:
- int i; };
- //演示潜在的危险
- //error: invalid conversion from `Foo**' to `const Foo**' /////////////////////////////////////////////////////////
- int main(int argc, char *argv[]) {
- const Foo x; Foo* p;
- //const Foo ** q = &p; //q now points to p; this is (fortunately!) an error
- const Foo ** q = const_cast<const Foo **>(&p); *q = &x; // p now points to x
- p->modify(); // Ouch: modifies a const Foo!! x.print(); // print: Foo_i:2
- return 0; }
我们定义了一个常量的Foo,常量Foo方法打印出来的永远为1;
Foo**到const Foo **的转换报错,
通过一个强转符让编译通过,
最后的x.print()的结果是2;这样的潜在危险在正式的项目代码中就很难发现;
很难会想到一个const对象还能够变更;
以上所述就是本文的全部内容了,希望大家能够喜欢。










