C++向函数传递指针

C++ Passing Pointer To A Function

本文关键字:指针 函数 C++      更新时间:2023-10-16

我在传递指向函数的指针时遇到问题。这是代码。

#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:UsersIvanDesktopExercise01.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);
||      ^

附言:在现实生活中,我不会用这个,但我已经投入其中,我想让它以这种方式工作。

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

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

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

int SetWeight(int *pWeight)
{
    (*pWeight)++;
    return *pWeight;
}
int *pWeight = &weight;

这将pWeight声明为指向int的指针。SetWeight实际上取了一个指向int的指针,所以您可以直接传入pWeight,而不需要任何其他限定符:

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

首先我接受了您的反馈并更改了:

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;

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