静态多态性(编译时可确定,一个类本身里有多个同名函数,-通过参数的不同区分调用的是哪个函数)--函数重载,运算符重载
动态多态性(运行时才可确定,基类和派生类中有同名函数,-通过基类指针访问基类和派生类的同名函数)-虚函数
基类和派生类有同名同参函数且未用virtual关键字,
则指向派生类对象的基类指针,调用到的是基类的成员函数display()。
如果将基类中的display()函数的定义改为virtual,即
test.cpp line 15改为
void virtual display()
则指向派生类对象的基类指针,调用到的是派生类的成员函数display()。
动态多态性(运行时才可确定,基类和派生类中有同名函数,-通过基类指针访问基类和派生类的同名函数)-虚函数
基类和派生类有同名同参函数且未用virtual关键字,
则指向派生类对象的基类指针,调用到的是基类的成员函数display()。
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
Student(int nu=1,string na="stu1",char se='f'):num(nu),name(na),sex(se){}
void display()
{
cout<<"num:"<<num<<endl;
cout<<"name:"<<name<<endl;
cout<<"sex:"<<sex<<endl;
}
private:
int num;
string name;
char sex;
};
class Student1:public Student//公用继承
{
public:
Student1(int nu=1,string na="stu1",char se='f',int ag=20,string ad="shanghai"):Student(nu,na,se)
{
age=ag;
address=ad;
}
void display()
{
cout<<"age:"<<age<<endl;
cout<<"address:"<<address<<endl;
}
private:
int age;
string address;
};
int main(int argc, char* argv[])
{
Student stu(3,"stu3",'m');
stu.display(); //是基类的display()
cout<<endl;
Student *pstu=&stu;;
pstu->display();//是基类的display()
cout<<endl;
Student1 stu1(6,"stu6",'f',20,"shenzhen");
stu1.display(); //是派生类的display()
cout<<endl;
pstu=&stu1;;
pstu->display();//是基类的display() or 派生类的display(),看结果
cout<<endl;
cout<<"sizeof(stu):"<<sizeof(stu)<<endl;
cout<<"sizeof(stu1):"<<sizeof(stu1)<<endl;
return 0;
}
num:3
name:stu3
sex:m
num:3
name:stu3
sex:m
age:20
address:shenzhen
num:6
name:stu6
sex:f
/*指向派生类对象的基类指针,调用到的是基类的成员函数display()。--未用virtual去修饰基类的display()
但尽管此时调用基类的display(),打印出的值也是派生类对象的值,因为此时this指针指向派生类对象。
*/
sizeof(stu):24
sizeof(stu1):44
Press any key to continue
如果将基类中的display()函数的定义改为virtual,即
test.cpp line 15改为
void virtual display()
则指向派生类对象的基类指针,调用到的是派生类的成员函数display()。
num:3//基类对象调用到的是基类的成员函数display()
name:stu3
sex:m
num:3//指向基类对象的基类指针,调用到的是基类的成员函数display()。
name:stu3
sex:m
age:20
address:shenzhen
/*派生类对象调用到的派生类的成员函数display(),因为基类的display()被派生类的同名同参函数覆盖掉了。
如果派生类中没有定义dispaly(),则调用到的是基类的display()。但尽管此时调用基类的display(),打印出的值也是派生类对象的值,因为此时this指针指向派生类对象。
num:6
name:stu6
sex:f
*/
age:20
address:shenzhen
/*指向派生类对象的基类指针,调用到的是派生类的成员函数display()。--使用了virtual去修饰基类的display()
如果派生类中没有定义dispaly(),则调用到的是基类的display()。但尽管此时调用基类的display(),打印出的值也是派生类对象的值,因为此时this指针指向派生类对象。
num:6
name:stu6
sex:f
*/
sizeof(stu):28
sizeof(stu1):48
Press any key to continue