C++——C++中的类型识别

发布时间:2026/7/28 1:16:42

C++——C++中的类型识别 1.在面向对象中可能出现下面的情况1基类指针指向子类对象2基类引用成为子类对象的别名静态类型——变量对象自身的类型动态类型——指针引用所指向对象的实际类型基类指针是否可以强制类型转换为子类指针取决于动态类型若指针指向子类就可以转换指向父类就无法转换所以C中如何得到动态类型解决方案利用多态在基类中定义虚函数返回具体的类型信息所有的派生类都必须实现类型相关的虚函数每个类中的类型虚函数都需要不同的实现#includeiostream #includestring using namespace std; class Base { public: virtual string type() { return Base; } }; class Derived :public Base { public: string type() { return Derived; } void print() { cout Derived endl; } }; class Child :public Base { public: string type() { return Child; } }; void test(Base* b) { // Derived* d static_castDerived*(b); 危险的转换方式 cout b-type() endl; if (b-type() Derived) { Derived* d static_castDerived*(b); d-print(); } cout dynamic_castDerived*(b) endl; //dynamic_cast只能显示转换是否成功但是无法知道转换后的结果 } int main() { Base b; Derived d; Child c; test(b); test(d); test(c); }运行结果Base0000000000000000DerivedDerived00000014E231F698Child0000000000000000但是上述方式的缺陷必须从基类开始提供类型虚函数所有的派生类都必须重写类型虚函数每个派生类的类型名必须唯一C提供了typeid关键字用于获取类型信息typeid关键字返回对应参数的类型信息typeid返回一个type_info类对象当typeid的参数为NULL时将抛出异常注意事项当参数为类型时返回静态类型信息当参数为变量时不存在虚函数表——返回静态类型信息存在虚函数表——返回动态类型信息#includeiostream #includestring #includetypeinfo using namespace std; class Base { public: }; class Derived :public Base { public: void printf() { cout Derived endl; } }; void test(Base* b) { const type_info tb typeid(*b); cout tb.name() endl; } int main() { int i 0; const type_info tiv typeid(i); const type_info tii typeid(int); cout (tiv tii) endl; //1 Base b; Derived d; test(b); //class Base test(d); //class Base return 0; }由于b指针所指向的对象没有虚函数表所有返回静态类型信息#includeiostream #includestring #includetypeinfo using namespace std; class Base { public: virtual ~Base() { } }; class Derived :public Base { public: void printf() { cout Derived endl; } }; void test(Base* b) { const type_info tb typeid(*b); cout tb.name() endl; } int main() { int i 0; const type_info tiv typeid(i); const type_info tii typeid(int); cout (tiv tii) endl; //1 Base b; Derived d; test(b); //class Base test(d); //class Derived return 0; }存在虚函数表——返回动态类型信息

相关新闻