c++快速入门8:多态

指向类

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 ;
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容

  • CPP 1、在main执行之前和之后执行的代码可能是什么? main函数执行之前,主要就是初始化系统相关资源: 设...
    voidFan阅读 1,657评论 1 6
  • 前言 前面我们已经介绍过了C++中的类与函数,不熟悉的,可以去看看NDK开发---C++学习(三):类与函数(上)...
    zhang_pan阅读 457评论 0 3
  • 程序设计基础(上) 前言 C++的常见错误 语法错误: 混淆结构体类型与结构体变量的区别,为一个结构体类型赋值。不...
    修Nya阅读 1,176评论 0 0
  • C++ 类 作者:AceTan,转载请标明出处! 0x00 面向对象与面向过程## 讨论类之前,我们有必要先探讨一...
    AceTan阅读 1,915评论 0 8
  • 为什么写这篇文章 本文算作是 《Android 音视频开发打怪升级》系列文章的“番外”篇,原本打算将本文的内容写在...
    开发的猫阅读 3,119评论 4 38