设为首页 加入收藏

TOP

GuruoftheWeek#6:正确使用const
2014-11-23 22:03:16 】 浏览:187
Tags:GuruoftheWeek#6: 正确 使用 const

问题:
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) );


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇计算机等级考试C语言上机考试改错.. 下一篇计算机C语言入门讲座―数组

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目