C++向函数传递指针
C++ Passing Pointer To A Function
我在传递指向函数的指针时遇到问题。这是代码。
#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++中可以有两种不同的含义。当在函数头中使用时,它们表示传递的变量是一个指针。当在指针前面的其他位置使用时,它指示指针指向的对象。看来你可能混淆了这些。
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址