簡體   English   中英

創建函數值,然后保存指針在全局指針數組值

[英]create value in function, then save pointer on value in global pointer array

我對c ++比較陌生,並且對Java習慣(我更喜歡)。 我這里有一些指針問題。 我創建了一個最小的程序來模擬更復雜程序的行為。

這是代碼:

void test (int);
void test2(int*);

int* global [5];    //Array of int-pointer

int main(int argc, char** argv) {
    int z = 3;
    int y = 5;      
    cin >> z;       // get some number
    global[0] = &y; // global 0 points on y

    test(z);        // the corpus delicti

    //just printing stuff
    cout << global[0]<<endl;   //target address in pointer
    cout << &global[0]<<endl;  //address of pointer
    cout << *global[0]<<endl;  //target of pointer

    return 0; //whatever
}


//function doing random stuff and calling test2
void test (int b){
    int i = b*b;
    test2(&i);
    return;
}

//test2 called by test puts the address of int i (defined in test) into global[0]
void test2(int* j){
   global[0]= j; 
}

棘手的部分是test2。 我將在測試中創建的變量的地址放入全局指針數組中。 不幸的是,該程序給了我一個編譯器錯誤:

main.cpp: In function 'int test(int)':
main.cpp:42:20: error: 'test2' was not declared in this scope
     return test2(&i);
                    ^

我在這里找不到任何范圍問題。 我嘗試將test的int i更改為全局變量,但這沒有幫助,所以我想這不是原因。

編輯:它現在編譯,但給cin = 20錯誤的值。 * global [0]應為400,但應為2130567168。這似乎不是int / uint問題。 距離2,14e9太遠了。 Edit2:輸入值無關緊要。

'test2' was not declared in this scope這是因為編譯器不知道什么是test2 您需要在主體上方添加一個函數原型。

void test (int b);
void test2(int& j);

要不就:

void test (int);
void test2(int&);

因為此時編譯器僅需要知道參數的類型,而不是它們的名稱。

編輯:將函數定義移至主要函數上方而不添加原型也可以,但是最好使用原型。

在調用一個函數之前,編譯器必須知道它。

因此,您可以重新排列函數定義,以使test2首先出現,然后是test ,最后是main ,或者在main之前放置test2test1聲明:

void test2(int& j); // declaration
void test(int b);   // declaration

int main(int argc, char** argv) {
    // ...
}

void test(int b){ // definition
    // ...
}

void test2(int& j) { // definition
    // ...
}

這將揭示一個更嚴重的錯誤; 您正在使用int*調用test2 ,但是它期望使用int& 您可以通過將調用轉換為test2(i);來解決此問題test2(i);


將函數整齊地划分為聲明和定義后,就可以對典型的C ++源文件管理進行下一步:將聲明放入頭文件(通常為*.h*.hpp ),並在實現中#include它們包含main文件(通常為*.cpp )。 然后為這兩個函數定義添加另外兩個實現文件。 在那里也添加相應的#include 不要忘記在標題中包含防護。

最后,分別編譯三個實現文件,並使用鏈接器根據三個結果對象文件創建可執行文件。

您需要在調用test2之前聲明它。 每個函數都需要在調用之前聲明。

在main上方添加這些行以聲明功能;

void test2(int& j);
void test2(int& j);

int main(){...}

暫無
暫無

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

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