C++RTTI(运行时类型识别)与异常处理解析

1:RTTI是在只有一个指向基类的指针或引用时所确定的一个对象的类型 

RTTI可以在程序运行时通过某一个对象的只恨确定该对象的类型,方便面向对象编程

测试代码如下

#include"stdafx.h"
#include"typeinfo.h"
#include"iostream.h"
class CB {

	virtual void dowork() {};
};
class CD1 :virtual public CB {

};
class CD2 :virtual CB{

};
class CD3 :public CD1, public CD2 {
public:
	//char* print(){ return "hello "; };
};
int main(int argc, char* argv[]) {
	//CB* p = new CD3();
	//cout << typeid(*p).name() << endl;
	//CD3* pd3 = dynamic_cast<CD3*>(p);
	//if (pd3)
		//cout << pd3->print() << endl;
}

2:异常处理 异常处理是程序设计中除调试之外的另一种错误处理方法 可以出错时不中断程序的执行

try{

}

catch{

}关键字来定义 

try里面一般是抛出异常 catch里面一般是异常 处理

测试代码如下

#include<typeinfo>
#include<iostream>
using namespace std;
class cexcept1{};
class cexcept2 {
public:
	cexcept2(cexcept1&e){}


};
int main(int argc, char* argv[]) {
try {
		throw cexcept1();
	}
	catch (cexcept2) {
		cout << "进入except2异常 处理器" << endl;
	}
	catch (cexcept1){
		cout << "进入except1异常处理器" << endl;
		}
}

猜你喜欢

转载自blog.csdn.net/jiebaoshayebuhui/article/details/126619086