同名成员的二义性(ambiguous)问题 class N N类 { public: int a; void display A类 B类 cout长<“N:a=& <<a<<endl; 3 C类 017年4月26日星期 第11章继承与派生 1 HOME 12时14分39秒 BACK NEXT
HOME2017年4月26日星期 三12时14分39秒 第11章 继承与派生 1 class N {public: int a; void display() { cout<<“N::a=“ <<a<<endl; } };
同名成员的二义性(ambiguous)问题 (1)两个基类有同名成员 -用基类名来限定,如cl.A:display(0; (2)两个基类和派生类都有同名成员 同名覆盖,派生类新增的同名成员覆盖了基类中 的同名成员 用基类名来限定,如cl.A:display0; (3)两个基类从同一个基类派生 通过直接基类名来限定,如cl.A:display(0; c1.N:displayO; 2017年4月26日星期 第12章多态性与虚函数 0雪2时14分39秒 BACK NEXT
HOME2017年4月26日星期 三12时14分39秒 第12章 多态性与虚函数 2 • (1) 两个基类有同名成员 – 用基类名来限定,如c1.A::display(); • (2) 两个基类和派生类都有同名成员 – 同名覆盖,派生类新增的同名成员覆盖了基类中 的同名成员 – 用基类名来限定,如c1.A::display(); • (3)两个基类从同一个基类派生 – 通过直接基类名来限定,如c1.A::display(); – c1.N::display();
基类与派生类的转换 1.派生类对象向基类对象赋值 2.派生类对象向基类对象的引用赋值或初始 化 3. 函数的参数是基类对象引用,相应的实参 可以用子类对象。 4.派生类对象的地址可以赋给指向基类对象 的指针变量 不论娜种方式都只能访问派生类中的基类成 员,而不能访问派生类增加的成员。 017年4月26日星期 HOME 第12章多态性与虚函数 12时14分39秒 NEX
HOME2017年4月26日星期 三12时14分39秒 第12章 多态性与虚函数 3 • 1. 派生类对象向基类对象赋值 • 2. 派生类对象向基类对象的引用赋值或初始 化 • 3. 函数的参数是基类对象引用,相应的实参 可以用子类对象。 • 4. 派生类对象的地址可以赋给指向基类对象 的指针变量。 • 不论哪种方式都只能访问派生类中的基类成 员,而不能访问派生类增加的成员
例11.10 出9g2m> using namespace std; class Student /声明Student类 public: St知dent(int,string,loat);/声明构造函数 void display(); private: Int num: string name: float score; tudent::Student(intnstring am,float s) 般哭ie盘带core客7 cout<<endl<<"num:"<<num<<endl; cout< name: <<name<<endl: cout<<"score:"<<score<<endl; class Graduate:public Student public: Graduate(int,string,float,float); /声明构造函数 void display(); ∥声明输出函数 private: float pay; 工资 : ostring nam,float s.float p):Student(n.nam,)pay(p) ay<cnd店 cout<<pay= int main() Student stud1(1001,"Li",87.5); Graduate grad1(2001,"Wang,98.5,563.5); Student pt=&studl: pt->display)月 /调用sl.display函数 t=&grad1: ot->display(): 捕猪指部ay函数 017年4月26日星期 第12章多态性与虚函数 4 HOME 12时14分39秒 BACK NEXT
HOME #include <iostream> #include <string> using namespace std; class Student //声明Student类 {public: Student(int, string,float); //声明构造函数 void display( ); private: int num; string name; float score; };Student::Student(int n, string nam,float s) { num=n; name=nam; score=s;} void Student::display( ) { cout<<endl<<"num:"<<num<<endl; cout<<"name:"<<name<<endl; cout<<"score:"<<score<<endl; }class Graduate:public Student {public: Graduate(int, string ,float,float); //声明构造函数 void display( ); //声明输出函数 private: float pay; //工资 };Graduate::Graduate(int n, string nam,float s,float p):Student(n,nam,s),pay(p){ } void Graduate::display() { Student::display(); cout<<"pay="<<pay<<endl; }int main() { Student stud1(1001,"Li",87.5); Graduate grad1(2001,"Wang",98.5,563.5); Student *pt=&stud1; pt->display( ); //调用stud1.display函数 pt=&grad1; //指针指向grad1 pt->display( ); //调用grad1.display函数 } 2017年4月26日星期 三12时14分39秒 第12章 多态性与虚函数 4
第12章 多态性与虚函数 Polymorphism & Virtual Functions 12.1 多态性的概念 12.2 一个典型的例子 12.3 虚函数 12.4纯虚函数与抽象类 2017年4月26日星期 第12章多态性与虚函数 5 HOMR 2时14分39秒 BACK NEXT
HOME2017年4月26日星期 三12时14分39秒 第12章 多态性与虚函数 5 12.1 多态性的概念 12.2 一个典型的例子 12.3 虚函数 12.4 纯虚函数与抽象类