-1
我想我沒有理解返回const的正確想法。修改const從函數返回
如果我有一個返回const值的函數,是不是說我返回後無法更改該值?
爲什麼編譯器允許我將const轉換爲非const變量?
或者它只適用於const指針?
const int foo(int index) {
return ++index;
}
int main(){
int i = foo(1); // why can I do this?
++i;
return 0;
}
一個'const int'可以很容易地複製,這就是將它分配給'i'時發生的情況。 'const'指針是不同的,因爲你指向*的*是'const',除非你有'const X * const',在這種情況下指針和目標都是'const'。看到[這樣的例子](http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const)的更多解釋。返回一個'const int'在任何情況下都是毫無意義的,因爲它們很便宜。 – tadman
請參閱http://stackoverflow.com/questions/6299967/what-are-the-use-cases-for-having-a-function-return-by-const-value-for-non-built和http:// stackoverflow.com/questions/8716330/purpose-of-returning-by-const-value獲取更多信息 – wkl
因此,通過值返回const是沒用的? @tadman – Dannz