C ++将指针传递给函数

时间:2014-11-03 20:59:31

标签: 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:在现实生活中,我不会使用它,但我进入了它,我想让它以这种方式工作。

4 个答案:

答案 0 :(得分:6)

你不应该取消引用指针。它应该是:

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

此外,在SetWeight()中,您正在递增指针而不是递增值,它应该是:

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

答案 1 :(得分:1)

int *pWeight = &weight;

这将pWeight声明为指向int的指针。 SetWeight实际上是指向int的指针,因此您可以直接传递pWeight而无需任何其他限定符:

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

答案 2 :(得分: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;

答案 3 :(得分:0)

*符号在C ++中可以有两种不同的含义。在函数头中使用时,它们表示传递的变量是指针。当在指针前面的其他地方使用时,它指示指针指向的位置。看来你可能会混淆这些。