#include <iostream>
using namespace std;
// 对象模型 类型兼容性原则
class Parent
{
public:
Parent()
{}
Parent(const Parent &obj)
{
cout << "拷贝构造被调用" << endl;
}
Parent& operator =(const Parent &obj)
{
cout << "赋值运算符重载函数被调用" << endl;
}
void setParent(int a, int b)
{
m_a = a;
m_b = b;
}
void showParent()
{
printf ("a = %d, b = %d\n", m_a, m_b);
}
public:
int m_a;
int m_b;
};
class Child : public Parent
{
public:
void setChild(int c, int d)
{
m_c = c;
m_d = d;
}
void showChild()
{
printf ("c = %d, d = %d\n", m_c, m_d);
}
public:
int m_c;
int m_d;
};
// 4、可以用派生类对象对基类对象进行构造、赋值
int main()
{
Child c1;
c1.setParent(1,2);
c1.setChild(3,4);
// Parent(const Parent &obj)
Parent p1 = c1; // ===> p1的拷贝 构造函数
// operator =(const Parent &obj)
p1 = c1; // 赋值运算符重载函数
return 0;
}
// 2、基类指针可以操作派生类对象
// 3、可以用基类的引用引用派生类对象
int main2()
{
Parent p1;
Child c1;
// Parent *pp1 = &p1;
// Child *pc1 = &c1;
// 指针能做的事情基于指针本身的类型,和他指向的对象类型无关
Parent *p2 = &c1;
p2->setParent(1,2);
p2->showParent();
Parent &p3 = c1; // Parent *const p3 = &c1
p3.showParent();
return 0;
}
// 1、父类对象存在的地方都能用派生类对象进行替换
int main1()
{
Parent p1;
Child c1;
p1.setParent(1,2);
p1.showParent();
c1.setParent(1,2);
c1.showParent();
return 0;
}
对象模型
最新推荐文章于 2024-03-01 16:06:02 发布