小弟请教前辈个关于继承的问题
小弟想在main.cpp里面写个函数,该函数的参数是一个基类(如:A)的某个继承类(如B,C其中之一);请教前辈,怎么能让函数识别传入的参数是那个继承类(究竟是B还是C)? 应当用什么办法实现这个东西那?
谢谢。
[解决办法]
百度搜索 rtti.
rtti 需要在编译之前启用rtti的编译选项才可以使用。
并且 rtti 需要基类具备多态性。
启用 rtti后,支持C++ type_id() 和 dynamic_cast.
如下例:
#include<iostream>
using namespace std;
class A
{
virtual void test() = 0;
};
class B : public A
{
void test()
{
cout << "this is b test()." << endl;
}
};
class C : public A
{
void test()
{
cout << "this is c test()." << endl;
}
};
void func(A* pParam)
{
B* p = NULL;
p = dynamic_cast<B*>(pParam);
if( p == NULL)
{
cout << "not b"<< endl;
}
else
{
cout << "is b"<<endl;
}
}
int main(int argc,char** argv)
{
A* b = new B();
A* c = new C();
func(b);
func(c);
delete b;
b = NULL;
delete c;
c = NULL;
return 0;
}