1 多态
只有指针,和引用才能表现 多态
#include <iostream>
using namespace std;
class Base{
public:
virtual void print(){
cout << "Base" << endl;
}
};
class D1 :public Base{
void print(){
cout << "D1" << endl;
}
};
class D2 :public Base{
void print(){
cout << "D2" << endl;
}
};
Base * get(int dType){
if (dType == 1)
return new D1();
else
return new D2();
}
int main()
{
D1 d1;
Base b1 = d1;
Base *b2 = & d1;
Base &b3 = d1;
b1.print(); // "Base"
b2->print(); //"Derived"
b3.print(); //"Derived"
Base *d4 = get(1); //“D1”运行期决定,表现多态
return 0;
}
多态的目的:
指相同对象收到不同消息或不同对象收到相同消息时产生不同的实现动作。C++支持两种多态性:编译时多态性,运行时多态性。
a、编译时多态性:通过重载函数实现
b、运行时多态性:通过虚函数实现。
封装:
封装的意义在于保护或者防止代码(数据)被我们无意中破坏。代码模块化,隐藏细节。
封装,也就是把客观事物封装成抽象的类,并且类可以把自己的数据和方法只让可信的类或者对象操作,对不可信的进行信息隐藏。
继承:
代码重用,表现多态
多态:
由同一个接口影响类型的封装 。接口重用
2 指针类型会 教导 编译器如何解释内存中的内容及大小