1.概述
1.基类指针可以在不进行显式类型转换的情况下指向派生类对象
2.基类引用可以在不进行显式类型转换的情况下引用派生类对象
3.引用兼容性属性可以将基类对象初始化为派生类对象,同样也可以将派生类对象赋给基类对象。
2.实例
2.1实例一
#include <iostream>
namespace SimpleTest
{
using namespace std;
class CParent
{
public:
CParent();
virtual ~CParent();
virtual void TestComFunc();
void TestParFunc();
private:
int m_nParValue;
};
CParent::CParent():m_nParValue(0)
{
cout<<"父类构造函数被调用"<<endl;
}
CParent::~CParent()
{
cout<<"父类析构函数被调用"<<endl;
}
void CParent::TestComFunc()
{
cout<<"父类方法(虚函数)被调用"<<endl;
}
void CParent::TestParFunc()
{
cout<<"父类方法被调用"<<endl;
}
class CSub : public CParent
{
public:
CSub();
~CSub();
void TestComFunc();
void TestSubFunc();
private:
int m_nSubValue;
};
CSub::CSub():m_nSubValue(0)
{
cout<<"子类构造函数被调用"<<endl;
}
CSub::~CSub()
{
cout<<"子类析构函数被调用"<<endl;
}
void CSub::TestComFunc()
{
cout<<"子类方法(重载父类方法)被调用"<<endl;
}
void CSub::TestSubFunc()
{
cout<<"子类方法被调用"<<endl;
}
}
int main()
{
SimpleTest::CParent* pMyClass = new SimpleTest::CSub;
pMyClass->TestComFunc();
/// 基类指针指向派生类对象,调用派生类重新定义的同名方法,最终取决于指向的派生类对象,"工程模式"的实现。
pMyClass->TestParFunc();
// pMyClass->TestSubFunc();
/// 基类指针指向派生类对象,只能调用派生类重新定义的基类同名方法,其他派生类公有函数成员无法调用。
delete pMyClass;
pMyClass = NULL;
/// 输出:
/// 父类构造函数被调用
/// 子类构造函数被调用
/// 子类方法(重载父类方法)被调用
/// 父类方法被调用
/// 子类析构函数被调用
/// 父类析构函数被调用
SimpleTest::CSub myClass;
SimpleTest::CParent& rMyClass = myClass;
rMyClass.TestComFunc();
rMyClass.TestParFunc();
/// 输出:
/// 父类构造函数被调用
/// 子类构造函数被调用
/// 子类方法(重载父类方法)被调用
/// 父类方法被调用
/// 子类析构函数被调用
/// 父类析构函数被调用
return 0;
}
2.2实例二
#include <iostream>
namespace SimpleTest
{
using namespace std;
class CParent
{
public:
CParent();
CParent(const CParent& OtherCParent);
virtual ~CParent();
CParent& operator=(const CParent& OtherCParent);
int GetParValue();
void SetParValue(int nValue);
private:
int m_nParVal;
};
CParent::CParent()
{
}
CParent::CParent(const CParent& OtherCParent)
{
m_nParVal = OtherCParent.m_nParVal;
std::cout<<"基类复制构造函数被调用"<<std::endl;
}
CParent::~CParent()
{
}
CParent& CParent::operator=(const CParent& OtherCParent)
{
m_nParVal = OtherCParent.m_nParVal;
std::cout<<"基类赋值函数被调用"<<std::endl;
return *this;
}
int CParent::GetParValue()
{
return m_nParVal;
}
void CParent::SetParValue(int nValue)
{
m_nParVal = nValue;
}
class CSub : public CParent
{
public:
CSub();
~CSub();
int GetSubValue();
void SetSubValue(int nValue);
};
CSub::CSub()
{
}
CSub::~CSub()
{
}
int CSub::GetSubValue()
{
return GetParValue();
}
void CSub::SetSubValue(int nValue)
{
SetParValue(nValue);
}
}
int main()
{
SimpleTest::CSub mySub;
mySub.SetSubValue(10);
std::cout<<mySub.GetSubValue()<<std::endl;
SimpleTest::CParent myParent(mySub);
/// 将myParent初始化为嵌套在CSub对象mySub中的CParent对象。
std::cout<<myParent.GetParValue()<<std::endl;
mySub.SetSubValue(20);
std::cout<<mySub.GetSubValue()<<std::endl;
myParent = mySub;
/// CSub对象mySub的基类部分被复制给myParent。
std::cout<<myParent.GetParValue()<<std::endl;
/// 输出:
/// 10
/// 基类复制构造函数被调用
/// 10
/// 20
/// 基类赋值函数被调用
/// 20
return 0;
}