checkedcast2.cpp

来自「C语言数值算法程序大全(第二版),课本文件」· C++ 代码 · 共 47 行

CPP
47
字号
//: C08:CheckedCast2.cpp
// From "Thinking in C++, 2nd Edition, Volume 2"
// by Bruce Eckel & Chuck Allison, (c) 2003 MindView, Inc.
// Available at www.BruceEckel.com.
// Uses RTTI's dynamic_cast
#include <iostream>
#include <vector>
#include "../purge.h"
using namespace std;

class Security {
public:
  virtual ~Security(){}
};
class Stock : public Security {};
class Bond : public Security {};
class Investment : public Security {
public:
  void special() {
    cout << "special Investment function\n";
  }
};
class Metal : public Investment {};

int main() {
  vector<Security*> portfolio;
  portfolio.push_back(new Metal);
  portfolio.push_back(new Investment);
  portfolio.push_back(new Bond);
  portfolio.push_back(new Stock);
  vector<Security*>::iterator it = 
    portfolio.begin();
  while(it != portfolio.end()) {
    Investment* cm = dynamic_cast<Investment*>(*it);
    if(cm) cm->special();
    else cout << "not a Investment" << endl;
    it++;
  }
  cout << "cast from intermediate pointer:\n";
  Security* sp = new Metal;
  Investment* cp = dynamic_cast<Investment*>(sp);
  if(cp) cout << "  it's a Commodity\n";
  Metal* mp = dynamic_cast<Metal*>(sp);
  if(mp) cout << "  it's a Metal too!\n";
  purge(portfolio);
} ///:~

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?