-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathgotw6.cpp
More file actions
65 lines (53 loc) · 1.21 KB
/
gotw6.cpp
File metadata and controls
65 lines (53 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Polygon {
public:
Polygon() : area_(-1) {}
void AddPoint(const Point& pt) {
InvalidateArea();
points_.push_back(pt);
}
Point GetPoint(int i) const {
return points_[i];
}
int GetNumPoints() const {
return points_.size();
}
double GetArea() const {
if( area_ < 0 ) // if not yet calculated and cached
CalcArea(); // calculate now
return area_;
}
private:
void InvalidateArea() { area_ = -1; }
void CalcArea() const {
area_ = 0;
vector<Point>::const iterator i;
for( i = points_.begin(); i != points_.end(); ++i )
area_ += /* some work */;
}
vector<Point> points_;
mutable double area_;
};
Polygon operator+( const Polygon& lhs, const Polygon& rhs ) {
Polygon ret = lhs;
int last = rhs.GetNumPoints();
for( int i = 0; i < last; ++i ) // concatenate
ret.AddPoint( rhs.GetPoint(i) );
return ret;
}
void f( const Polygon& poly ) {
const_cast<Polygon&>(poly).AddPoint( Point(0,0) );
}
void g( Polygon& const rPoly ) {
rPoly.AddPoint( Point(1,1) );
}
void h( Polygon* const pPoly ) {
pPoly->AddPoint( Point(2,2) );
}
int main() {
Polygon poly;
const Polygon cpoly;
f(poly);
f(cpoly);
g(poly);
h(&poly);
}