2014-11-03 89 views
0

傳遞指向函數的指針時遇到問題。這是代碼。C++將指針傳遞給某個函數

#include <iostream> 

using namespace std; 

int age = 14; 
int weight = 66; 

int SetAge(int &rAge); 
int SetWeight(int *pWeight); 

int main() 
{ 
    int &rAge = age; 
    int *pWeight = &weight; 

    cout << "I am " << rAge << " years old." << endl; 
    cout << "And I am " << *pWeight << " kg." << endl; 

    cout << "Next year I will be " << SetAge(rAge) << " years old." << endl; 
    cout << "And after a big meal I will be " << SetWeight(*pWeight); 
    cout << " kg." << endl; 
    return 0; 
} 

int SetAge(int &rAge) 
{ 
    rAge++; 
    return rAge; 
} 

int SetWeight(int *pWeight) 
{ 
    *pWeight++; 
    return *pWeight; 
} 

我的編譯器輸出這樣的:

|| C:\Users\Ivan\Desktop\Exercise01.cpp: In function 'int main()': 
Exercise01.cpp|20 col 65 error| invalid conversion from 'int' to 'int*' [-fpermissive] 
|| cout << "And after a big meal I will be " << SetWeight(*pWeight); 
||                ^
Exercise01.cpp|9 col 5 error| initializing argument 1 of 'int SetWeight(int*)' [-fpermissive] 
|| int SetWeight(int *pWeight); 
|| ^

PS:在現實生活中我不會用這個,但我進入它,我想獲得它以這種方式工作。

回答

6

您不應該取消引用指針。它應該是:

cout << "And after a big meal I will be " << SetWeight(pWeight); 

此外,在SetWeight(),你是遞增的指針,而不是增加值,應該是:

int SetWeight(int *pWeight) 
{ 
    (*pWeight)++; 
    return *pWeight; 
} 
+0

這樣做,但我的輸出是「」一頓大餐後,我將-1公斤「 – 2014-11-03 21:02:57

+0

修正了它,我需要將* pWeight ++;改爲* pWeight + = 1;現在它可以正常工作,謝謝。 – 2014-11-03 21:11:24

1
int *pWeight = &weight; 

這聲明pWeight作爲一個指針intSetWeight其實需要一個指向int,所以你可以通過pWeight直,沒有任何其他限定:

cout << "And after a big meal I will be " << SetWeight(pWeight); 
+0

但我的輸出是「」一頓大餐後我將-1公斤「 – 2014-11-03 21:06:09

+0

修正了它。我需要改變* pWeight ++; to * pWeight + = 1;現在它可以工作。謝謝。 – 2014-11-03 21:12:12

0

首先,我把你的反饋和改變:

cout << "And after a big meal I will be " << SetWeight(*pWeight); 
// to 
cout << "And after a big meal I will be " << SetWeight(pWeight); 

// But after that I changed also: 
*pWeight++; 
// to 
*pWeight += 1; 
0

符號*可以有兩種C++中的不同含義。在函數頭中使用時,它們表示要傳遞的變量是一個指針。當在指針前面的其他地方使用時,指示指針指向哪個指針。看起來你可能會混淆這些。