#include "stdafx.h"
#include <conio.h>
#include <iostream>
#include <string>
using namespace std;
using namespace std;


class CParent
  {
public:
 CParent() {}

//以下在构造函数是初始化成员列表,多个用逗号隔开
 CParent(string strName,int age):strName(strName),m_age(age) {}
 virtual string GetName() {return strName;}
private:
string strName;
int m_age;
};


class CChild:public CParent
  {
public:
//初始化成员列表父类与本类的成员
//加入explicit关键字,防止隐式类型转换
 explicit CChild(string strName):CParent("Parent:"+strName,34),strName("Child:"+strName) {}
 string GetName() {return strName;}
private:
string strName;
};


int _tmain(int argc, _TCHAR* argv[])
  {
int pause;

//调用父类构造
CParent parent("parent",56);
cout<<parent.GetName()<<endl;

//调用子类构造
CChild child("sky");
cout<<child.GetName()<<endl;

//子类构造有加explicit,不可以稳式转换
//CChild child1 = "explicitTest";
//cout<<child1.GetName()<<endl;

//1.static_cast类型转换
//a.指针转换
CParent *pParent=NULL;
pParent = static_cast<CParent*>(&child) ;
cout<<pParent->GetName()<<endl;//调用的是CChild类的GetName

//b.对象间转换
CParent tmpParent;
//tmpParent = (CParent)child;
tmpParent = static_cast<CParent>(child) ;
cout<<tmpParent.GetName()<<endl;//调用的是父类GetName,因为tmpParent是Cparent对象
//虚表不起作用

//2.dynamic_cast类型转换
CChild *pChild1;
CChild *pChild2;
pChild1 = dynamic_cast<CChild*>(&parent);//将返回空指针
pChild2 = static_cast<CChild*>(&parent); //返回的是parent地址.但调用子类的方法,将不安全
 /**//*dynamic_cast支持交叉转换
如果B继承A,C也继承A.
那么将B用static_cast转成C是编译错误
将B用dynamic_cast转成C返回NULL指针
*/


//3.const_cast
const CParent *constParent=NULL;
CParent *pParent1 = const_cast<CParent*>(constParent);

//4.reinterpret_cast
//最底层的重新解释
//reinterpret_cast原原本本的位复制,而static_cast有内部解析转换
int n=9;
double d1=reinterpret_cast<double & > (n);
cout<<d1<<endl;

double d2 = static_cast<double>(n);
cout<<d2<<endl;

_getch();
return 0;
}


|