基类TableTennisPlayer 派生类RatedPlayer
1. 基类指针可以在不进行显示类型转换的情况下指向派生类对象;基类引用可以在不进行显示类型转换的情况下引用派生类对象.
RatedPlayer palyer(1000,”Mallory”,true)
TableTennisPlayer &rt = palyer;
TableTennisPlayer *pt = palyer;
2. 不可以将基类对象和地址赋给派生类引用和指针
TableTennisPlayer palyer(1000,“Betsy”);
RatedPlayer&rt = palyer; ///NOT ALLOWED
RatedPlayer*pt = palyer; ///NOT ALLOWED
3. 如果没有使用virtual,将根据引用类型或指针类型选择方法,如果使用了virtual,将根据引用或指针指向的对象来选择方法.
class Brass
{
private:
string m_name;
intm_age;
public:;
Brass(conststring name,int age):m_name(name),m_age(age){};
virtual void study(){cout<<"jackis studying C++"<<endl;}
voidlove(){cout<<"Brass love"<<endl;}
};
class BrassPluse:publicBrass
{
private:
string m_company;
public:
BrassPluse(conststring &name,int age,const string &company):Brass(name,age),m_company(company){};
virtual void study(){cout<<"jackis studying C++ in Tencent "<<endl;}
voidlove(){cout<<"BrassPluse love"<<endl;}
};
void main()
{
Brass dom("jack",24);
BrassPluse doc("jack",24,"Tencent");
Brass & rt =dom;
Brass & rc =doc;
///定义virtual
rt.study();
rc.study();
///没有定义virtual
rt.love();
rc.love();
system("pause");
}