📄 shapev2.cpp
字号:
//: C:ShapeV2.cpp
// From Thinking in C++, 2nd Edition
// at http://www.BruceEckel.com
// (c) Bruce Eckel 1999
// Copyright notice in Copyright.txt
// Alternative to ShapeV.cpp
#include <iostream>
#include <vector>
#include "../purge.h"
using namespace std;
class Shape {
Shape(Shape&); // No copy-construction
protected:
Shape() {} // Prevent stack objects
// But allow access to derived constructors
public:
enum type { tCircle, tSquare, tTriangle };
virtual void draw() = 0;
virtual ~Shape() { cout << "~Shape\n"; }
static Shape* make(type);
};
class Circle : public Shape {
Circle(Circle&); // No copy-construction
Circle operator=(Circle&); // No operator=
protected:
Circle() {};
public:
void draw() { cout << "Circle::draw\n"; }
~Circle() { cout << "~Circle\n"; }
friend Shape* Shape::make(type t);
};
class Square : public Shape {
Square(Square&); // No copy-construction
Square operator=(Square&); // No operator=
protected:
Square() {};
public:
void draw() { cout << "Square::draw\n"; }
~Square() { cout << "~Square\n"; }
friend Shape* Shape::make(type t);
};
class Triangle : public Shape {
Triangle(Triangle&); // No copy-construction
Triangle operator=(Triangle&); // Prevent
protected:
Triangle() {};
public:
void draw() { cout << "Triangle::draw\n"; }
~Triangle() { cout << "~Triangle\n"; }
friend Shape* Shape::make(type t);
};
Shape* Shape::make(type t) {
Shape* S;
switch(t) {
case tCircle: S = new Circle; break;
case tSquare: S = new Square; break;
case tTriangle: S = new Triangle; break;
}
S->draw(); // Virtual function call
return S;
}
int main() {
vector<Shape*> shapes;
cout << "virtual constructor calls:" << endl;
shapes.push_back(Shape::make(Shape::tCircle));
shapes.push_back(Shape::make(Shape::tSquare));
shapes.push_back(Shape::make(Shape::tTriangle));
cout << "virtual function calls:\n";
for(int i = 0; i < shapes.size(); i++)
shapes[i]->draw();
//!Circle c; // Error: can't create on stack
purge(shapes);
} ///:~
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -