指向类
OOP的三个基石是封装、继承和多态性。
术语 "多态性"(来自希腊语polymorphism,意思是 "多种形式")描述了根据实体的上下文赋予其不同含义或目的的能力。
在C++中,重载运算符可以被描述为多态性的。C++类方法也可以是多态的。理解类的多态性的关键是认识到可以创建基类指针,该指针也可以通过关联绑定到特定的派生类。
基类的指针可以被分配给派生类的内存地址,以提供 "上下文"--唯一地识别该派生类。例如,用一个Base基类和一个派生的Sub类,可以像这样创建一个指针。

#include <iostream>
using namespace std ;
class Base
{
public:
//Use default constructor & destructor.
void Identify( long adr ) const { cout << "Base class called by 0x" << hex << adr << endl ; }
} ;
class SubA : public Base
{
// Empty.
} ;
class SubB : public Base
{
// Empty.
} ;
int main()
{
Base* ptrA = new SubA ; // or... SubA a ; Base* ptrA = &a ;
Base* ptrB = new SubB ; // or... SubB b ; Base* ptrB = &b ;
ptrA -> Identify((long) &ptrA);
ptrA -> Identify((long) &ptrB);
return 0 ;
}
调用虚拟方法
绑定到特定派生类的基类指针可以用来调用从基类继承的派生类方法。然而,派生类特有的方法必须通过实例对象来调用。绑定到特定派生类的基类指针也可以使用:: 范围解析操作符来明确调用基类中的方法。
最有用的是,当基类方法被声明为 "虚拟 "方法时,派生类中的继承方法可以重写基类中的方法。
#include <iostream>
using namespace std ;
class Parent
{
public:
void Common() const { cout << "I am part of this family, " ; }
virtual void Identify() const { cout << "I am the parent" << endl ; }
} ;
class Child : public Parent
{
public :
void Identify() const { cout << "I am the child" << endl ; }
} ;
class Grandchild : public Child
{
public :
void Identify() const { cout << "I am the grandchild" << endl ; }
void Relate() const { cout << "Grandchild has parent and grandparent" << endl ; }
} ;
int main()
{
Child son ;
Grandchild grandson ;
Parent* ptrChild = &son ;
Parent* ptrGrandchild = &grandson ;
ptrChild -> Common() ;
ptrChild -> Identify( ) ;
ptrGrandchild -> Common() ;
ptrGrandchild -> Identify( ) ;
ptrChild -> Parent::Common() ;
ptrChild -> Parent::Identify( ) ;
grandson.Relate() ;
return 0 ;
}
引导方法调用
具有多个派生类对象的多态性的最大优点是,对同名方法的调用被引导到适当的覆盖方法。

#include <iostream>
using namespace std ;
class Bird
{
public :
virtual void Talk() const { cout << "A bird talks..." << endl ; }
virtual void Fly() const { cout << "A bird flies..." << endl ; }
} ;
class Pigeon : public Bird
{
public:
// Use default constructor & destructor.
//Declare overriding methods.
virtual void Talk() const { cout << "Coo! Coo!" << endl ; }
virtual void Fly() const { cout << "A pigeon flies away..." << endl ; }
} ;
class Chicken : public Bird
{
public:
// Use default constructor & destructor.
// Declare overriding methods.
virtual void Talk() const { cout << "Cluck! Cluck!" << endl ; }
virtual void Fly() const { cout << "I\'m just a chicken - I can\'t fly!" << endl ; }
} ;
int main()
{
Bird* pPigeon = new Pigeon ;
Bird* pChicken = new Chicken ;
pPigeon -> Talk() ;
pPigeon -> Fly() ;
pChicken -> Talk() ;
pChicken -> Fly() ;
pPigeon -> Bird::Talk() ;
pChicken -> Bird::Fly() ;
return 0 ;
}
提供能力类
允许其他类从其派生的类被称为 "能力类"--它们向派生类提供能力。
能力类通常不包含数据,而只是声明了一些可以在派生类中被重写的虚拟方法。
//=============================================
// C++ Programming in easy steps 5ed. [8:140]
//=============================================
#include <iostream>
using namespace std ;
class Bird
{
public :
virtual int Talk() const { return -1 ; }
virtual int Fly() const { return -1 ; }
} ;
class Pigeon : public Bird
{
public:
// Use default constructor & destructor.
// Declare overriding methods.
virtual int Talk() const { cout << "Coo! Coo!" << endl ; return 0 ; }
virtual int Fly() const { cout << "A pigeon flies away..." << endl ; return 0 ; }
} ;
class Chicken : public Bird
{
public:
// Use default constructor & destructor.
// Declare overriding methods.
virtual int Talk() const { cout << "Cluck! Cluck!" << endl ; return 0 ; }
virtual int Fly() const { cout << "I\'m just a chicken - I can\'t fly!" << endl ; return 0 ; }
} ;
int main()
{
Bird* pPigeon = new Pigeon ;
Bird* pChicken = new Chicken ;
pPigeon -> Talk() ;
pChicken -> Talk() ;
pPigeon -> Bird::Talk() ;
if( -1 ) { cout << "Error! - Program ended." << endl ; return 0 ; }
pPigeon -> Fly() ;
pChicken -> Fly() ;
return 0 ;
}
抽象数据类型
抽象数据类型(ADT:Abstract Data Type)代表了概念,而不是有形的对象,并且总是其他类的基础。基类可以通过将方法初始化为0而成为ADT。这些方法被称为 "纯虚拟方法",必须始终在派生类中被重写。
#include <iostream>
using namespace std ;
class Shape
{
public :
virtual int getArea() = 0 ;
virtual int getEdge() = 0 ;
virtual void Draw() = 0 ;
} ;
class Rect : public Shape
{
private :
int width, height ;
public :
Rect( int initHeight, int initWidth ) // Constructor.
{
width = initWidth ;
height = initHeight ;
}
~Rect() ; // Destructor.
int getArea() { return height * width ; }
int getEdge() { return (2 * height) + ( 2 * width) ; }
void Draw()
{
for( int i = 0 ; i < height ; i++ )
{
for( int j = 0 ; j < width ; j++ )
{
cout << "x " ;
}
cout << endl ;
}
}
} ;
int main()
{
Shape* pQuad = new Rect( 3, 7 ) ;
Shape* pSquare = new Rect( 5, 5 ) ;
pQuad -> Draw() ;
cout << "Area is " << pQuad -> getArea() << endl ;
cout << "Perimeter is " << pQuad -> getEdge() << endl ;
pSquare -> Draw() ;
cout << "Area is " << pSquare -> getArea() << endl ;
cout << "Perimeter is " << pSquare -> getEdge() << endl ;
return 0 ;
}
复杂的层次结构
ADT派生出ADT可构建复杂的层次结构的类。这提供了很大的灵活性,而且是完全可以接受的,只要每个纯方法在派生类的某个点上被定义。
#include <iostream>
using namespace std ;
class Boat
{
protected :
int length ;
public :
int getLength() { return length ; }
virtual void Model() = 0 ;
} ;
class Sailboat : public Boat
{
protected :
int mast ;
public :
int getMast() { return mast ; }
virtual void Boom() = 0 ;
} ;
隔离类结构
本书中每个示例程序的源代码一般都包含在一个.cpp文件中以节省空间,但实际上OOP程序通常包含在三个独立的文件中。
- *.h文件--只包含类的声明。
- .cpp文件 - 包含实现头文件中声明的方法的类定义,该文件由#include指令引用。
- Client.cpp文件

ops.h
class Calculator
{
public :
Calculator() ;
void launch() ;
void readInput() ;
void writeOutput() ;
bool run() ;
private :
double num1, num2 ;
char oper ;
bool status ;
} ;
ops.cpp
#include "ops.h"
#include <iostream>
using namespace std ;
Calculator::Calculator() { status = true ; }
void Calculator::launch()
{
cout << endl << "*** SUM CALCULATOR ***" << endl ;
cout << "Enter a number, an operator(+,-,*,/), and another number." << endl << "Hit Return to calculate. Enter zero to exit." << endl ;
}
void Calculator::readInput()
{
cout << "> " ; cin >> num1 ;
if( num1 == 0 ) status = false ;
else { cin >> oper ; cin >> num2 ; }
}
void Calculator::writeOutput()
{
if (status) switch(oper)
{
case '+' : { cout << ( num1 + num2 ) << endl ; break ; }
case '-' : { cout << ( num1 - num2 ) << endl ; break ; }
case '*' : { cout << ( num1 * num2 ) << endl ; break ; }
case '/' : if( num2 != 0 ) cout << ( num1 / num2 ) << endl ;
else cout << "Cannot divide by zero" << endl ;
}
}
bool Calculator::run()
{
return status ;
}
sum.cpp
#include "ops.h"
// Client
int main()
{
Calculator* pCalc = new Calculator ;
pCalc -> launch() ;
while ( pCalc -> run() )
{
pCalc -> readInput() ;
pCalc -> writeOutput() ;
}
return 0 ;
}
网友评论