C++编程思想 第1卷 第15章 多态性和虚函数 继承和VTABLE

当实现继承和重新定义一些虚函数时,编译器对新类创建一个新VTABLE表,
并且插入新函数的地址,对于没有重新定义的虚函数使用基类函数的地址

派生类中继承或增加新的虚函数时会发生什么呢?

//: C15:AddingVirtuals.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Adding virtuals in derivation
#include <iostream>
#include <string>
using namespace std;

class Pet {
  string pname;
public:
  Pet(const string& petName) : pname(petName) {}
  virtual string name() const { return pname; }
  virtual string speak() const { return ""; }
};

class Dog : public Pet {
  string name;
public:
  Dog(const string& petName) : Pet(petName) {}
  // New virtual function in the Dog class:
  virtual string sit() const {
    return Pet::name() + " sits";
  }
  string speak() const { // Override
    return Pet::name() + " says 'Bark!'";
  }
};

int main() {
  Pet* p[] = {new Pet("generic"),new Dog("bob")};
  cout << "p[0]->speak() = "
       << p[0]->speak() << endl;
  cout << "p[1]->speak() = "
       << p[1]->speak() << endl;
//! cout << "p[1]->sit() = "
//!      << p[1]->sit() << endl; // Illegal
  getchar();
} ///:~

类Pet中含有2个虚函数: speak()和name(),而在类Dog中又增加了第3个称为
sit()的函数,并且重新定义了speck()的含义

编译器在Dog的VTABLE中把speak()的地址准确地映射到和Pet的VTABLE中
同样的位置

编译器只对指向基类对象的指针工作

基类只有speak()和name()函数,所以它就是编译器唯一允许调用的函数

RTTI是有关向下类型转换基类指针到派生类指针的问题

输出
p[0]->speak() =
p[1]->speak() = bob says 'Bark!'

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81351718
今日推荐