函数正如:
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。
本文详细解析了C++中const关键字的三种不同用途,并通过具体示例代码展示了如何利用const来确保函数不修改对象状态。同时,文章还讨论了返回局部对象引用时可能遇到的问题及其原因。

被折叠的 条评论
为什么被折叠?



