demo_type_cast_5_const_cast_2.cpp

来自「对于一个初涉VC++的人来书」· C++ 代码 · 共 42 行

CPP
42
字号

//***************************************************
// const_cast 去掉const属性
//***************************************************

# include <iostream.h>

class A
{
public:
	A(int i):value(i),amount(0) {}
	~A() { cout<<value<<" was reported "<<amount<<" times"<<endl; }
	void report() const;
private:
	int value;
	int amount; //Number of times the object is reported
};

void A::report() const
{
	const_cast<A *>(this)->amount++;
	cout<<value<<endl;
}

int main()
{
	const A a(123);

	a.report();
	a.report();
	a.report();

	return 0;
}

/*
123
123
123
123 was reported 3 times
Press any key to continue
*/

⌨️ 快捷键说明

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