castaway.cpp

来自「ThinkingC++中文版」· C++ 代码 · 共 32 行

CPP
32
字号
//: C08:Castaway.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// "Casting away" constness

class Y {
  int i;
public:
  Y();
  void f() const;
};

Y::Y() 
{ 
	i = 0; 
}

void Y::f() const 
{
//!  i++; // Error -- const member function
  ((Y*)this)->i++; // OK: cast away const-ness
  // Better: use C++ explicit cast syntax:
  (const_cast<Y*>(this))->i++;
}

void main() {
  const Y yy;
  yy.f(); // Actually changes it!
} ///:~

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?