2014-11-03 47 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++中的不同含义。在函数头中使用时,它们表示要传递的变量是一个指针。当在指针前面的其他地方使用时,指示指针指向哪个指针。看起来你可能会混淆这些。