文档介绍:Chapter 11Inheritance and Polymorphism
§ Concept of Inheritance
§ Accessibility in Inheritance
§ Constructor/Destructor in Inheritance
§ Multiple Inheritance
§ Redefining Functions
§ Virtual Function and Polymorphism
§ Abstract Classes
§ Dynamic Casting
1
2
§ Concept of Inheritance (继承)
The “is a” relationship
Apple is a fruit
Elephant is an animal
Circle is a shape
A is a B
A has the characteristics/features/properties of B
A inherits B
Class A inherits class B
Inheritance can extend existing classes!
3
Class Inheritance
Syntax:
B
A
基类父类超类
Base Parent Super-Class
派生类子类
Derived-Class Child
class DerivedClass : acckeyword BaseClass{…};
class A: public B{
public:
…
private:
…
};
B
A
4
Example of Inheritance
TestGeometricObject
Run
5
A Tip about Generic Programming(泛型编程)
With inheritance, an object of a derived class can be used wherever an object of the base class is required
This is a kind of GP
GP permits mon functions or types that differ only in the types operated on
Template (模板) (in Chapter 15) is the main GP technique in C++
void showArea(GeometricObject gb){…};
Circle cl;
Rectangle rt;
showArea( cl); showArea(rt);
6
§ Accessibility in Inheritance
The protected Keyword
A protected data field or function can be accessed by name in its derived classes
class B {
public:
int i;
protected:
int j;
private:
int k;
};
class A: public B{
public:
void display(){
cout << i << endl;
cout << j << endl;
cout << k << endl;
}
};
int main(){
A a;
cout << << endl;
cout << << endl;
cout << << endl;
();
return 0;
}
7
Summary of Accessibility Keyword
Keyword
In Class
Itself
In Derived Class
In Others
public
√
√
√
protected
√
√
╳
private
√
╳
╳
8
Accessibility after Inheritance
Accessibility in Base
Inheritance
Accessibility in Derive