我不斷收到這2個錯誤在我的代碼C++初學者的錯誤,作業
In function 'int main()': error: invalid initialization of non-const reference of type 'int&' from a temporary of type 'int' error: in passing argument 1 of 'void swapInt(int&, int&)'
但我有真正的問題是swapInt。我需要接受2個整數 ,然後用它們的參數切換它們的值,所以曾經是a的現在b 以及曾經b的現在是a。請幫忙!
void swapInt (int &a, int &b);
int main() {
int a = 1;
int b = 2;
swapInt(1, 2);
cout << a << " " << b;
return 0;
}
void swapInt (int &a, int &b) {
int c = a;
a = b;
b = c;
//cout << a << " " << b;
}
你聲明變量'a'和'b',但是你不使用它們。您將文字傳遞給函數(1和2),而不是引用它們存儲的整數。嘗試在'main()'的開頭設置'a = 1'和'b = 2',然後調用'swapInt(a,b)'。 – ely 2012-03-25 02:00:09
你必須明白,你在'main'中定義的'a'與'swapInt'中的'a'無關......後面的概念被稱爲「變量範圍」。 – 2012-03-25 02:03:41
小心點。交換1和2將大大延長時空結構,所有公式如1 + 1 = 2會變成2 + 2 = 1!你不想和宇宙一起玩這樣的遊戲! – 2012-03-25 02:17:28