1.
联编是指一个程序模块、代码之间互相关联的过程。
静态联编,是程序的匹配、连接在编译阶段实现,也称为早期匹配。重载函数使用静态联编。
动态联编是指程序联编推迟到运行时进行,所以又称为晚期联编。switch 语句和 if 语句是动态联编的例子。
2.
静态联编:
普通成员函数重载可表达为两种形式:
<1>在一个类说明中重载
<2>基类的成员函数在派生类重载:根据参数的特征加以区分;使用“ :: ”加以区分;根据类对象加以区分
基类指针和派生类指针与基类对象和派生类对象4种可能匹配:
直接用基类指针引用基类对象;
直接用派生类指针引用派生类对象;
用基类指针引用一个派生类对象;
用派生类指针引用一个基类对象。
3.
基类指针引用派生类对象:基类指针可以通过派生类对象访问所有从基类继承的元素,但不能用基类指针访问派生类自定义的元素(除非用了显示类型转换)
派生类指针引用基类对象:
派生类指针只有经过强制类型转换之后,才能引用基类对象
冠以关键字 virtual 的成员函数称为虚函数
实现运行时多态的关键首先是要说明虚函数,另外,必须用基类指针调用派生类的不同实现版本
联编是指一个程序模块、代码之间互相关联的过程。
静态联编,是程序的匹配、连接在编译阶段实现,也称为早期匹配。重载函数使用静态联编。
动态联编是指程序联编推迟到运行时进行,所以又称为晚期联编。switch 语句和 if 语句是动态联编的例子。
2.
静态联编:
普通成员函数重载可表达为两种形式:
<1>在一个类说明中重载
<2>基类的成员函数在派生类重载:根据参数的特征加以区分;使用“ :: ”加以区分;根据类对象加以区分
基类指针和派生类指针与基类对象和派生类对象4种可能匹配:
直接用基类指针引用基类对象;
直接用派生类指针引用派生类对象;
用基类指针引用一个派生类对象;
用派生类指针引用一个基类对象。
3.
基类指针引用派生类对象:基类指针可以通过派生类对象访问所有从基类继承的元素,但不能用基类指针访问派生类自定义的元素(除非用了显示类型转换)
#include<iostream>
#include<cstring>
using namespace std ;
class A_class
{ char name[20] ;
public : void put_name( char * s ) { strcpy_s( name, s ) ; }
void show_name() { cout << name << "\n" ; }
};
class B_class : public A_class
{ char phone_num[ 20 ] ;
public : void put_phone( char * num ) { strcpy_s ( phone_num , num ) ; }
void show_phone() { cout << phone_num << "\n" ; }
};
int main()
{ A_class * A_p ; //基类指针
A_class A_obj ;
B_class B_obj ;
A_p = & A_obj ;
A_p -> put_name( "Wang xiao hua" ) ; A_p -> show_name() ;
A_p = & B_obj ;//基类指针指向派生类对象
A_p -> put_name( "Chen ming" ) ; A_p -> show_name() ; //调用从基类继承的成员函数
B_obj.put_phone ( "5555_12345678" );//用派生类对象调用派生类的成员函数
( ( B_class * ) A_p ) -> show_phone() ;//对基类指针强类型转换调用派生类的成员函数
}
4.派生类指针引用基类对象:
派生类指针只有经过强制类型转换之后,才能引用基类对象
#include<iostream>
#include<cstring>
using namespace std ;
class Date
{ public:
Date( int y, int m, int d ) { SetDate( y, m, d ); }
void SetDate( int y, int m, int d ) { year = y ; month = m ; day = d ; }
void Print() { cout << year << '/' << month << '/' << day << "; " ; }
protected : int year , month , day ;
} ;
class DateTime : public Date
{ public :
DateTime( int y, int m, int d, int h, int mi, int s ) : Date( y, m, d ) { SetTime( h, mi, s ); }
void SetTime( int h, int mi, int s ) { hours = h; minutes = mi; seconds = s; }
void Print()
{ ( ( Date * ) this ) -> Print();//对 this 指针作类型转换调用基类成员函数,等价于Date :: Print();
cout << hours << ':' << minutes << ':' << seconds << '\n' ;
}
private: int hours , minutes , seconds ;
};
int main()
{ DateTime dt( 2009, 1, 1, 12, 30, 0 ) ;
dt.Print() ;
}
5.冠以关键字 virtual 的成员函数称为虚函数
实现运行时多态的关键首先是要说明虚函数,另外,必须用基类指针调用派生类的不同实现版本
#include<iostream>
using namespace std ;
class Base
{ public : Base(char xx) { x = xx; }
void who() { cout << "Base class: " << x << "\n" ; }
protected: char x;
} ;
class First_d : public Base
{ public : First_d(c