放牧代码和思想
专注自然语言处理、机器学习算法
    This thing called love. Know I would've. Thrown it all away. Wouldn't hesitate.

C++ dynamic_cast 笔记

这个全局函数或者叫库函数利用RTTI来转换指针或引用的类型,注意转换指针的时候不会抛异常,只有在转引用的时候才会抛异常:

#include <iostream>
using namespace std;

class People
{
public:
	People()
	{
		cout << "People constructed" << endl;
	}
	virtual void speak() = 0;
};

class Man:public People
{
public:
	void speak()
	{
		cout << "A man speaks" << endl;
	}

	void fight()
	{
		cout << "A man fights" << endl;
	}
};

class Woman:public People
{
private:
	Man son;
	int cookTimes;
public:
	void speak()
	{
		cout << "A woman speaks" << endl;
	}

	void cook()
	{
		cout << "A woman cooks" << endl;
		cookTimes++;
	}

	Man getSon()
	{
		cout << "A woman's son:" << endl;
		return son;
	}
};

///////////////////////////SubMain//////////////////////////////////
int main(int argc, char *argv[])
{
	People *p = new Man();
	p->speak();
	Man *m = dynamic_cast<Man *>(p);
	m->fight();
	Man *m2 = (Man *)p;
	m2->fight();

	try
	{
		Woman *w = dynamic_cast<Woman *>(p);
		if (w != NULL)
		{
			w->cook();
			w->getSon().speak();
		}
	}
	catch(bad_cast &e)
	{
		// 指针转换不会抛异常
		cout << "bad_cast exception" << endl;
	}

	cout << "-----------------" << endl;
	try
	{
		Woman w = dynamic_cast<Woman &>(*p);
		w.cook();
		w.getSon().speak();
	}
	catch(bad_cast &e)
	{
		cout << "bad_cast exception" << endl;
	}
	
	delete p;
	system("pause");
	return 0;
}
///////////////////////////End Sub//////////////////////////////////
/************************************************************************/
/* output:
People constructed
A man speaks
A man fights
A man fights
-----------------
bad_cast exception
*/
/************************************************************************/

知识共享许可协议 知识共享署名-非商业性使用-相同方式共享码农场 » C++ dynamic_cast 笔记

评论 欢迎留言

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

我的作品

HanLP自然语言处理包《自然语言处理入门》