#include<iostream>
using namespace std;
class Base
{
public:
void Method1()
{
cout << "This is Base's method1." << endl;
}
virtual void Method2()
{
cout << "This is Base's method2." << endl;
}
};
class Derive :public Base
{
public:
void Method1()
{
cout << "This is Derive's method1." << endl;
}
void Method2()
{
cout << "This is Derive's method2." << endl;
}
public:
int m_num;
};
int main()
{
Base b;
b.Method1();
Derive d;
d.Method1();
Base *p1 = &d;
p1->Method1();//调用的是Base类中的方法
//Derive *p2 = &b;//编译报错,派生类无法引用其父类
//int num = p1->m_num;//编译报错,父类无法引用子类的数据成员
Base &q1 = d;
q1.Method1();//调用的是Base类中的方法
Base &q2 = d;
q2.Method2();//调用的是Derive类中的方法
Base b1 = d;//将调用拷贝构造函数
b1.Method2();//调用的是Base类中的方法
//Derive d1 = (Derive)b;//编译报错,无法将父类对象强制转换成子类
/*
结论:
①指针和引用本质上意义相同,所以在多态性上体现的功能是一致的;
②C++中,子类对象可以转换为父类型,而无法将父类对象强制转换为子类型;
③父类指针或引用无法访问子类新增的数据成员;
*/
system("pause");
return 0;
}
C++父类和子类的关系以及指针和引用在派生中起到的作用
最新推荐文章于 2024-06-27 17:11:04 发布