您的位置:首页 > 编程语言 > C语言/C++

C++多态的实现条件

2015-01-29 21:59 155 查看
#include <iostream>
class Person{
public:
virtual void say(){
std::cout<<"person"<<std::endl;
}
};
class Student:public Person{
public:
void say(){
std::cout<<"student"<<std::endl;
}
};
int main(){
Person per;
Student stud;
per.say();
stud.say();
//传递对象
per = stud;
per.say();
//指针
Person *pPtr = &stud;
pPtr->say();
//引用
Person &pRef = stud;
pRef.say();
}


1. 基类中用virtual关键字表明方法
2. 采用父类的引用和指针调用多态方法,父类对象本身不能实现多态
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: