C++传递函数指针
我在将指针传递到函数时遇到问题。这是代码C++传递函数指针,c++,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
#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:在现实生活中,我不会使用这个,但我进入了它,我想让它以这种方式工作。你不应该取消指针的引用。应该是:
cout << "And after a big meal I will be " << SetWeight(pWeight);
int SetWeight(int *pWeight)
{
(*pWeight)++;
return *pWeight;
}
这将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++中可以有两个不同的含义。在函数头中使用时,它们表示传递的变量是指针。当在指针前面的其他位置使用时,它表示指针指向的对象。看起来你可能把这些搞错了。做了,但我的产量是在一顿大餐后,我将被-1公斤修正。我需要改变*pWeight++;至*pWeight+=1;现在它开始工作了。谢谢。我做了,但我的产量是在一顿大餐后,我会被-1公斤修正。我需要改变*pWeight++;至*pWeight+=1;现在它开始工作了。谢谢
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;