问题:
const是写出更安全的代码的一个利器.而且它还可以帮助编译器进行优化.应该尽可能的多用...但是什么才叫做"尽可能"呢
不对下面程序的结构和其他风格问题作挑剔,因为它仅仅是用来做示例说明.请只在合适的地方简单的加上或删除"const"(包括一些变量和相关的关键字).附加题是:哪些地方将使程序由于const的错误使用而产生编译错误或不确定的(undefined)结果
class Polygon {
public:
Polygon() : area_(-1) {}
void AddPoint( const Point pt ) {
InvalidateArea();
points_.push_back(pt);
}
Point GetPoint( const int i ) {
return points_[i];
}
int GetNumPoints() {
return points_.size();
}
double GetArea() {
if( area_ < 0 ) // if not yet calculated and cached
CalcArea(); // calculate now
return area_;
}
private:
void InvalidateArea() { area_ = -1; }
void CalcArea() {
area_ = 0;
vector
::iterator i;
for( i = points_.begin(); i != points_.end(); ++i )
area_ += /* some work */;
}
vector
points_;
double area_;
};
Polygon operator+( Polygon& lhs, 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
(poly).AddPoint( Point(0,0) );