簡體   English   中英

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:\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);

另外,在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 ++中可以有兩種不同的含義。 當在函數頭中使用時,它們指示要傳遞的變量是指針。 當在指針前面的其他地方使用時,它指示指針指向的對象。 看來您可能對此感到困惑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM