本文参照于狄泰软件学院,唐佐林老师的——《C++深度剖析教程》
我们在父子间的冲突发现,可以定义一个虚函数来解决父类指针(引用)引发的同名覆盖的问题。
在面向对象中还可能出现下面的情况:
1. 基类指针指向子类对象
2. 基类引用成为子类对象的别名
静态类型与动态类型
- 静态类型:变量(对象)自身的类型
- 动态类型:指针(引用)所指向对象的实际类型
表达式的静态类型在编译时总是已知的,它是变量声明时的类型或表达式生成的类型,动态类型则是变量或表达式表示的内存中的对象的类型。动态类型直到运行时才可知。
那么我们是否可以将父类类型强制转换为子类类型呢?强制转换会成功吗?
基类指针是否可以强制类型转换为子类指针取决于动态类型!
那么,C++中如何得到动态类型?
利用多态特性获取动态类型
思路:利用多态特性
1. 在基类中定义虚函数返回具体的类型信息
2. 所有的派生类都必须实现类型相关的虚函数
3. 每个类中的类型虚函数都需要不同的实现
示例代码:动态类型识别
#include <iostream>
#include <string>
using namespace std;
class Base
{
public:
virtual string type()
{
return "Base";
}
};
class Derived : public Base
{
public:
string type()
{
return "Derived";
}
void printf()
{
cout << "I'm a Derived." << endl;
}
};
class Child : public Base
{
public:
string type()
{
return "Child";
}
};
void test(Base* b)
{
// Derived* d = static_cast<Derived*>(b);
if( b->type() == "Derived" )
{
Derived* d = static_cast<Derived*>(b);
d->printf();
}
cout << dynamic_cast<Derived*>(b) << endl;
}
int main(int argc, char *argv[])
{
Base b;
Derived d;
Child c;
test(&b);
test(&d);
test(&c);
return 0;
}
输出结果:
0
I’m a Derived.
0x6cff08
0
我们可以发现程序中的一些缺陷,
1. 强制类型转换是不一定成功的。
2. 必须从基类开始提供类型转换虚函数
3. 所有的派生类都必须重写类型转换函数
4. 每个派生类的类型名必须唯一
C++的解决方案:类型识别关键字
- C++提供了typeid关键字用于获取类型信息
- typeid关键字返回对应参数的类型信息
- typeif返回一个type_info类对象
- 当typeid的参数为NULL时抛出异常
- 当参数为类型时:返回静态类型信息
- 当参数为变量时:
不存在虚函数表则返回静态类型信息
存在虚函数表则返回动态类型信息
示例代码:typeid类型识别
#include <iostream>
#include <string>
#include <typeinfo>
using namespace std;
class Base
{
public:
virtual ~Base()
{
}
};
class Derived : public Base
{
public:
void printf()
{
cout << "I'm a Derived." << endl;
}
};
void test(Base* b)
{
const type_info& tb = typeid(*b);
cout << tb.name() << endl;
}
int main(int argc, char *argv[])
{
int i = 0;
const type_info& tiv = typeid(i);
const type_info& tii = typeid(int);
cout << (tiv == tii) << endl;
Base b;
Derived d;
test(&b);
test(&d);
return 0;
}