The difference between the C ++ static_cast and dynamic_cast

dynamic_cast operator, a pointer or reference to the base class safely converted into a pointer or reference to the derived class.

When we both operators for certain types of pointer or reference, and which contains a virtual function type, the operator uses the pointer or reference object bound dynamic type

Used in three forms

dynamic_cast <type *> (e) // e must be a pointer
dynamic_cast <type &> (e) // e must be a left-value
// e dynamic_cast <type &&> ( e) can not be left value

//有虚函数
class A
{
public:
	A() {}
	virtual ~A() {}
};

class B :public A
{
public:
	B() {}
	virtual ~B() {}
};

class C :public B
{
public:
	C() {}
	virtual ~C() {}
};

class D :public B, public A
{
public:
	D() {}
	virtual ~D() {}
};


//没有虚函数
class E
{
public:
	E() {}
	~E() {}
	void get() 
	{
		printf("eeeeeeeeeeee\n");
	}
};

class F:public E
{
public:
	F() {}
	~F() {}
	void get() 
	{
		printf("ffffffffffff\n");
	}
};

int main()
{
	A *pa = new C;
	if (B *pb = dynamic_cast<B*>(pa))
	{
		cout << "True" << endl;
	}
	else
	{
		cout << "False" << endl;
	}//因为指针类型的转换失败返回为0可以使用条件中赋值判断

	try
	{
//		D &cp = dynamic_cast<D&>(*pa);//错误 只能派生类转父类
		C &cp = dynamic_cast<C&>(*pa);//正确,*pa的类型是C  
		cout << "cp" << endl;
	}
	catch (std::bad_cast e)
	{
		cout << e.what() << endl;
	}//引用类型失败返回的是bad_cast  

	B *pbb = new B;
//	if (C *pc = static_cast<C*>(pbb)) //用static_cast 则可以转成功
	if (C *pc = dynamic_cast<C*>(pbb))
	{
		cout << "True" << endl;
	}
	else
	{
		cout << "False" << endl;
	}

	A *paa = new D;
	if (B *pc = dynamic_cast<B*>(paa))
	{
		cout << "True" << endl;
	}
	else
	{
		cout << "False" << endl;
	}

	E* pe = new E;
	E* pf = new F;

//	F* pg = dynamic_cast<F*>(pe); //基类转派生类 必须要有虚函数
	F* pg = static_cast<F*>(pe);  //使用static_cast 不会报错 但是有可能是不安全的
//	E* pg = dynamic_cast<E*>(pf); //派生类转基类 怎么转都是安全的
	printf("%d\n",&pg);
	//get 未定义成虚函数 不能形成多态
	pe->get(); // eeeeeeeeeee
	pf->get(); // eeeeeeeeeee


	system("pause");
	return 0;
}

This article intercept c ++ primer Fifth Edition 730

Published 43 original articles · won praise 1 · views 2300

Guess you like

Origin blog.csdn.net/lpl312905509/article/details/104046600