C++基礎知識易錯點和易混淆總結匯總(不定時更新)
阿新 • • 發佈:2018-12-30
以下是我本人不定時更新的易錯點彙總,如需轉載,請註明出處。
1、對指標的引用
int a = 10;
int *p = &a; //初始化指標p。
int* &pa = p; //這個是對指標p的引用、在我們使用pa的操作。相當於對p的操作
2、函式返回值的行為
...
int add(int a, int b)
{
return a + b ;
}
....
int a = 1;
int b = 2;
int c = add(a, b); //create temporary, delete it after executing this statement
...
上面的程式碼中,在 int c = add (a, b);時,發生瞭如下事情:
首先:建立了一個臨時物件,如temp。
然後:將函式的返回值 a+ b 的副本 複製給 temp;
最後:將temp 的副本複製給 變數 c,並刪除臨時變數 temp
下面給出一個常見的錯誤:
#include <iostream> #include <string> using namespace std; const float pi = 3.14f; float f; //全域性變數 //返回一個float float fun1(float r) { f = r*r*pi; return f; } //返回一個引用 float& fun2(float r) { f = r*r*pi; return f; } int main() { float fun1(float=5); //正確:預設引數呼叫 float& fun2(float=5); //正確:預設引數呼叫 float a = fun1(); ////正確 float& b= fun1(); //錯誤:返回值會儲存到一個臨時變數temp,對一個臨時變數的引用 //會出問題的 float& c= fun2(); //正確 這種方式直接返回一個全域性變數的引用,是最節省記憶體空間的 //但是也是容易出問題,要注意所引用變數的有效期,此處,全域性 //變數的引用明顯比c的有效期長。所以是安全的 getchar(); return 0; }
持續更新中!!!!!!