解析C++编程中virtual声明的虚函数以及单个继承

所属分类: 软件编程 / C 语言 阅读数: 80
收藏 0 赞 0 分享

虚函数

虚函数是应在派生类中重新定义的成员函数。 当使用指针或对基类的引用来引用派生的类对象时,可以为该对象调用虚函数并执行该函数的派生类版本。
虚函数确保为该对象调用正确的函数,这与用于进行函数调用的表达式无关。
假定基类包含声明为 virtual 的函数,并且派生类定义了相同的函数。 为派生类的对象调用派生类中的函数,即使它是使用指针或对基类的引用来调用的。 以下示例显示了一个基类,它提供了 PrintBalance 函数和两个派生类的实现

// deriv_VirtualFunctions.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

class Account {
public:
  Account( double d ) { _balance = d; }
  virtual double GetBalance() { return _balance; }
  virtual void PrintBalance() { cerr << "Error. Balance not available for base type." << endl; }
private:
  double _balance;
};

class CheckingAccount : public Account {
public:
  CheckingAccount(double d) : Account(d) {}
  void PrintBalance() { cout << "Checking account balance: " << GetBalance() << endl; }
};

class SavingsAccount : public Account {
public:
  SavingsAccount(double d) : Account(d) {}
  void PrintBalance() { cout << "Savings account balance: " << GetBalance(); }
};

int main() {
  // Create objects of type CheckingAccount and SavingsAccount.
  CheckingAccount *pChecking = new CheckingAccount( 100.00 ) ;
  SavingsAccount *pSavings = new SavingsAccount( 1000.00 );

  // Call PrintBalance using a pointer to Account.
  Account *pAccount = pChecking;
  pAccount->PrintBalance();

  // Call PrintBalance using a pointer to Account.
  pAccount = pSavings;
  pAccount->PrintBalance();  
}

在前面的代码中,对 PrintBalance 的调用是相同的,pAccount 所指向的对象除外。 由于 PrintBalance 是虚拟的,因此将调用为每个对象定义的函数版本。 派生类 PrintBalance 和 CheckingAccount 中的 SavingsAccount 函数“重写”基类 Account 中的函数。
如果声明的类不提供 PrintBalance 函数的重写实现,则使用基类 Account 中的默认实现。
派生类中的函数仅在基类中的虚函数的类型相同时重写这些虚函数。 派生类中的函数不能只是与其返回类型中的基类的虚函数不同;参数列表也必须不同。
当使用指针或引用调用函数时,以下规则将适用:
根据为其调用的对象的基本类型来解析对虚函数的调用。
根据指针或引用的类型来解析对非虚函数的调用。
以下示例说明在通过指针调用时虚函数和非虚函数的行为:

// deriv_VirtualFunctions2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;

class Base {
public:
  virtual void NameOf();  // Virtual function.
  void InvokingClass();  // Nonvirtual function.
};

// Implement the two functions.
void Base::NameOf() {
  cout << "Base::NameOf\n";
}

void Base::InvokingClass() {
  cout << "Invoked by Base\n";
}

class Derived : public Base {
public:
  void NameOf();  // Virtual function.
  void InvokingClass();  // Nonvirtual function.
};

// Implement the two functions.
void Derived::NameOf() {
  cout << "Derived::NameOf\n";
}

void Derived::InvokingClass() {
  cout << "Invoked by Derived\n";
}

int main() {
  // Declare an object of type Derived.
  Derived aDerived;

  // Declare two pointers, one of type Derived * and the other
  // of type Base *, and initialize them to point to aDerived.
  Derived *pDerived = &aDerived;
  Base  *pBase  = &aDerived;

  // Call the functions.
  pBase->NameOf();      // Call virtual function.
  pBase->InvokingClass();  // Call nonvirtual function.
  pDerived->NameOf();    // Call virtual function.
  pDerived->InvokingClass(); // Call nonvirtual function.
}

输出

Derived::NameOf
Invoked by Base
Derived::NameOf
Invoked by Derived

请注意,无论 NameOf 函数是通过指向 Base 的指针还是通过指向 Derived 的指针进行调用,它都会调用 Derived 的函数。 它调用 Derived 的函数,因为 NameOf 是虚函数,并且 pBase 和 pDerived 都指向类型 Derived 的对象。
由于仅为类类型的对象调用虚函数,因此不能将全局函数或静态函数声明为 virtual。
在派生类中声明重写函数时可使用 virtual 关键字,但它不是必需的;虚函数的重写始终是虚拟的。
必须定义基类中的虚函数,除非使用 pure-specifier 声明它们。 (有关纯虚函数的详细信息,请参阅抽象类。)
可通过使用范围解析运算符 (::) 显式限定函数名称来禁用虚函数调用机制。 考虑先前涉及 Account 类的示例。 若要调用基类中的 PrintBalance,请使用如下所示的代码:

CheckingAccount *pChecking = new CheckingAccount( 100.00 );

pChecking->Account::PrintBalance(); // Explicit qualification.

Account *pAccount = pChecking; // Call Account::PrintBalance

pAccount->Account::PrintBalance();  // Explicit qualification.

在前面的示例中,对 PrintBalance 的调用将禁用虚函数调用机制。


单个继承
在“单继承”(继承的常见形式)中,类仅具有一个基类。考虑下图中阐释的关系。

2016122145736303.jpeg (121×102)

简单单继承关系图
注意该图中从常规到特定的进度。在大多数类层次结构的设计中发现的另一个常见特性是,派生类与基类具有“某种”关系。在该图中,Book 是一种 PrintedDocument,而 PaperbackBook 是一种 book。
该图中的另一个要注意的是:Book 既是派生类(来自 PrintedDocument),又是基类(PaperbackBook 派生自 Book)。此类类层次结构的框架声明如下面的示例所示:

// deriv_SingleInheritance.cpp
// compile with: /LD
class PrintedDocument {};

// Book is derived from PrintedDocument.
class Book : public PrintedDocument {};

// PaperbackBook is derived from Book.
class PaperbackBook : public Book {};

PrintedDocument 被视为 Book 的“直接基”类;它是 PaperbackBook 的“间接基”类。差异在于,直接基类出现在类声明的基础列表中,而间接基类不是这样的。
在声明派生的类之前声明从中派生每个类的基类。为基类提供前向引用声明是不够的;它必须是一个完整声明。
在前面的示例中,使用访问说明符 public。 成员访问控制中介绍了公共的、受保护的和私有的继承的含义。
类可用作多个特定类的基类,如下图所示。

2016122145806415.jpeg (486×156)

注意
有向非循环图对于单继承不是唯一的。它们还用于表示多重继承关系图。 多重继承中对本主题进行了说明。
在继承中,派生类包含基类的成员以及您添加的所有新成员。因此,派生类可以引用基类的成员(除非在派生类中重新定义这些成员)。当在派生类中重新定义了直接或间接基类的成员时,范围解析运算符 (::) 可用于引用这些成员。请看以下示例:

// deriv_SingleInheritance2.cpp
// compile with: /EHsc /c
#include <iostream>
using namespace std;
class Document {
public:
  char *Name;  // Document name.
  void PrintNameOf();  // Print name.
};

// Implementation of PrintNameOf function from class Document.
void Document::PrintNameOf() {
  cout << Name << endl;
}

class Book : public Document {
public:
  Book( char *name, long pagecount );
private:
  long PageCount;
};

// Constructor from class Book.
Book::Book( char *name, long pagecount ) {
  Name = new char[ strlen( name ) + 1 ];
  strcpy_s( Name, strlen(Name), name );
  PageCount = pagecount;
};

请注意,Book 的构造函数 (Book::Book) 具有对数据成员 Name 的访问权。在程序中,可以创建和使用类型为 Book 的对象,如下所示:

// Create a new object of type Book. This invokes the
//  constructor Book::Book.
Book LibraryBook( "Programming Windows, 2nd Ed", 944 );

...

// Use PrintNameOf function inherited from class Document.
LibraryBook.PrintNameOf();

如前面的示例所示,以相同的方式使用类成员和继承的数据和函数。如果类 Book 的实现调用 PrintNameOf 函数的重新实现,则只能通过使用范围解析 (Document) 运算符来调用属于 :: 类的函数:

// deriv_SingleInheritance3.cpp
// compile with: /EHsc /LD
#include <iostream>
using namespace std;

class Document {
public:
  char *Name;     // Document name.
  void PrintNameOf() {} // Print name.
};

class Book : public Document {
  Book( char *name, long pagecount );
  void PrintNameOf();
  long PageCount;
};

void Book::PrintNameOf() {
  cout << "Name of book: ";
  Document::PrintNameOf();
}

如果存在可访问的明确基类,则可以隐式将派生类的指针和引用转换为其基类的指针和引用。下面的代码使用指针演示了此概念(相同的原则适用于引用):

// deriv_SingleInheritance4.cpp
// compile with: /W3
struct Document {
  char *Name;
  void PrintNameOf() {}
};

class PaperbackBook : public Document {};

int main() {
  Document * DocLib[10];  // Library of ten documents.
  for (int i = 0 ; i < 10 ; i++)
   DocLib[i] = new Document;
}

在前面的示例中,创建了不同的类型。但是,由于这些类型都派生自 Document 类,因此存在对 Document * 的隐式转换。因此,DocLib 是“异类列表”(其中包含的所有对象并非属于同一类型),该列表包含不同类型的对象。
由于 Document 类具有一个 PrintNameOf 函数,因此它可以打印库中每本书的名称,但它可能会忽略某些特定于文档类型的信息(Book 的页计数、HelpFile 的字节数等)。
注意
强制使用基类来实现函数(如 PrintNameOf)通常不是最佳设计。 虚函数提供其他设计替代方法。


更多精彩内容其他人还在看

用标准c++实现string与各种类型之间的转换

这个类在头文件中定义, < sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本
收藏 0 赞 0 分享

C++如何通过ostringstream实现任意类型转string

再使用整型转string的时候感觉有点棘手,因为itoa不是标准C里面的,而且即便是有itoa,其他类型转string不是很方便。后来去网上找了一下,发现有一个好方法
收藏 0 赞 0 分享

C/C++指针小结

要搞清一个指针需要搞清指针的四方面的内容:指针的类型,指针所指向的类型,指针的值或者叫指针所指向的内存区,还有指针本身所占据的内存区
收藏 0 赞 0 分享

C++ 类的静态成员深入解析

在C++中类的静态成员变量和静态成员函数是个容易出错的地方,本文先通过几个例子来总结静态成员变量和成员函数使用规则,再给出一个实例来加深印象
收藏 0 赞 0 分享

C++类的静态成员初始化详细讲解

通常静态数据成员在类声明中声明,在包含类方法的文件中初始化.初始化时使用作用域操作符来指出静态成员所属的类.但如果静态成员是整型或是枚举型const,则可以在类声明中初始化
收藏 0 赞 0 分享

C++类静态成员与类静态成员函数详解

静态成员不可在类体内进行赋值,因为它是被所有该类的对象所共享的。你在一个对象里给它赋值,其他对象里的该成员也会发生变化。为了避免混乱,所以不可在类体内进行赋值
收藏 0 赞 0 分享

C++中的friend友元函数详细解析

友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类。友元函数的特点是能够访问类中的私有成员的非成员函数。友元函数从语法上看,它与普通函数一样,即在定义上和调用上与普通函数一样
收藏 0 赞 0 分享

static全局变量与普通的全局变量的区别详细解析

以下是对static全局变量与普通的全局变量的区别进行了详细的分析介绍,需要的朋友可以过来参考下,希望对大家有所帮助
收藏 0 赞 0 分享

C++ explicit关键字的应用方法详细讲解

C++ explicit关键字用来修饰类的构造函数,表明该构造函数是显式的,既然有"显式"那么必然就有"隐式",那么什么是显示而什么又是隐式的呢?下面就让我们一起来看看这方面的知识吧
收藏 0 赞 0 分享

教你5分钟轻松搞定内存字节对齐

随便google一下,人家就可以跟你解释的,一大堆的道理,我们没怎么多时间,讨论为何要对齐.直入主题,怎么判断内存对齐规则,sizeof的结果怎么来的,请牢记以下3条原则
收藏 0 赞 0 分享
查看更多