举一个函数说明C++里的 const

来源:互联网 发布:mysql建立表 编辑:程序博客网 时间:2024/06/10 03:44

函数正如:

 

const SpreadsheetCell SpreadsheetCell::add(const SpreadsheetCell &cell) const{    SpreadsheetCell newCell;    newCell.set(mValue + cell.mValue);    return (newCell);}


其中,第一个const是指函数返回的对象的数据不能被改变;

第二个const 用法同第一个;

第三个const是指该函数保证不会修改任何数据成员

 

顺便说一下,这个方法返回一个对象(newCell)的副本,即新建一片内存空间存放这个副本。如果是返回引用时,就会存在问题,看下面

 

const SpreadsheetCell& SpreadsheetCell::add(const SpreadsheetCell &cell) const{    SpreadsheetCell newCell;    newCell.set(mValue + cell.mValue);    return (*newCell);}


 这里存在一个问题就是,当add方法调用完后,newCell出了作用域,会被销毁。返回的引用将成为悬挂引用,即引用的内在空间不是newCell。