⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shapev.cpp

📁 Thinking in C++ 2nd edition source code which are all the cores of the book Thinking in C++ second e
💻 CPP
字号:
//: C:ShapeV.cpp
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// "Virtual constructors"
// Used in a simple "Shape" framework
#include <iostream>
#include <vector>
#include "../purge.h"
using namespace std;

class Shape {
  Shape* S;
  // Prevent copy-construction & operator=
  Shape(Shape&);
  Shape operator=(Shape&);
protected:
  Shape() { S = 0; };
public:
  enum type { tCircle, tSquare, tTriangle };
  Shape(type);  // "Virtual" constructor
  virtual void draw() { S->draw(); }
  virtual ~Shape() {
    cout << "~Shape\n";
    delete S;
  }
};

class Circle : public Shape {
  Circle(Circle&);
  Circle operator=(Circle&);
public:
  Circle() {}
  void draw() { cout << "Circle::draw\n"; }
  ~Circle() { cout << "~Circle\n"; }
};

class Square : public Shape {
  Square(Square&);
  Square operator=(Square&);
public:
  Square() {}
  void draw() { cout << "Square::draw\n"; }
  ~Square() { cout << "~Square\n"; }
};

class Triangle : public Shape {
  Triangle(Triangle&);
  Triangle operator=(Triangle&);
public:
  Triangle() {}
  void draw() { cout << "Triangle::draw\n"; }
  ~Triangle() { cout << "~Triangle\n"; }
};

Shape::Shape(type t) {
  switch(t) {
    case tCircle: S = new Circle; break;
    case tSquare: S = new Square; break;
    case tTriangle: S = new Triangle; break;
  }
  draw();  // Virtual call in the constructor
}

int main() {
  vector<Shape*> shapes;
  cout << "virtual constructor calls:" << endl;
  shapes.push_back(new Shape(Shape::tCircle));
  shapes.push_back(new Shape(Shape::tSquare));
  shapes.push_back(new Shape(Shape::tTriangle));
  cout << "virtual function calls:" << endl;
  for(int i = 0; i < shapes.size(); i++)
    shapes[i]->draw();
  Shape c(Shape::tCircle); // Can create on stack
  purge(shapes);
} ///:~

⌨️ 快捷键说明

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