PageRenderTime 21ms CodeModel.GetById 14ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Examples/lua/owner/example.cxx

#
C++ | 69 lines | 53 code | 14 blank | 2 comment | 5 complexity | 8544e25cbe19bdb7e9061881b73d58aa MD5 | raw file
 1/* File : example.c */
 2
 3#include "example.h"
 4#include <stdio.h>
 5
 6#define M_PI 3.14159265358979323846
 7
 8/* Move the shape to a new location */
 9void Shape::move(double dx, double dy) {
10  x += dx;
11  y += dy;
12}
13
14int Shape::nshapes = 0;
15
16double Circle::area(void) {
17  return M_PI*radius*radius;
18}
19
20double Circle::perimeter(void) {
21  return 2*M_PI*radius;
22}
23
24double Square::area(void) {
25  return width*width;
26}
27
28double Square::perimeter(void) {
29  return 4*width;
30}
31
32Circle* createCircle(double w)
33{
34    return new Circle(w);
35}
36
37Square* createSquare(double w)
38{
39    return new Square(w);
40}
41
42ShapeOwner::ShapeOwner() {printf("  ShapeOwner(%p)\n",this);}
43ShapeOwner::~ShapeOwner()
44{
45    printf("  ~ShapeOwner(%p)\n",this);
46    for(unsigned i=0;i<shapes.size();i++)
47        delete shapes[i];
48}
49
50void ShapeOwner::add(Shape* ptr) // this method takes ownership of the object
51{
52    shapes.push_back(ptr);
53}
54
55Shape* ShapeOwner::get(int idx) // this pointer is still owned by the class (assessor)
56{
57    if (idx < 0 || idx >= static_cast<int>(shapes.size()))
58        return NULL;
59    return shapes[idx];
60}
61
62Shape* ShapeOwner::remove(int idx) // this method returns memory which must be deleted
63{
64    if (idx < 0 || idx >= static_cast<int>(shapes.size()))
65        return NULL;
66    Shape* ptr=shapes[idx];
67    shapes.erase(shapes.begin()+idx);
68    return ptr;
69}