我有一個函式 ( attempt_volume_exchange_move),我在其中定義了一個結構 ( status)。我想將status變數傳遞給我在attempt_volume_exchange_move( store_box_properties) 中呼叫的函式。嘗試為 撰寫代碼時store_box_properties,我在 CLion 上收到以下警告訊息:
'struct status' 的宣告在這個函式之外是不可見的。
說明我的問題的代碼如下:
struct boxes {
// Member 1
// Member 2
// Member 3
// ...
// Member N
} box_dense, box_rare;
void attempt_volume_exchange_move(void) {
struct status {
struct boxes box_dense, box_rare;
} original, new;
store_box_properties(&original.box_dense);
store_box_properties(&original.box_rare);
}
void store_box_properties(struct status *status_pointer) { // Line where the warning message is given
// Code for store_box_properties
}
我該如何解決這個問題?我想過建立status一個全球結構;然而,這似乎很浪費,因為 的定義status僅在attempt_volume_exchange_move. 我試圖以最“正確”/“適當”/“優雅”的方式解決這個問題。
在此先感謝您的任何見解!
uj5u.com熱心網友回復:
目前,您有兩個不同的同名結構宣告。第一個在函式內attempt_volume_exchange_move
void attempt_volume_exchange_move(void) {
struct status {
struct boxes box_dense, box_rare;
} original, new;
//...
在功能塊范圍之外是不可見的。
函式引數串列中的第二個 store_box_properties
void store_box_properties(struct status *status_pointer)
這在函式之外也是不可見的。
由于這兩個函式必須參考相同的結構,因此應該在函式之外宣告和定義該結構。
您可以通過在每個函式中定義兼容的區域結構并通過指向 void 的指標將結構型別的物件從一個函式傳遞到另一個函式來完成您想要做的事情。在第二個函式中,您可以將指標強制轉換為該函式中宣告的結構型別的指標。
但這使得代碼不清晰且難以修改。
注意在您提供的代碼中,這些呼叫中使用的引數運算式
store_box_properties(&original.box_dense);
store_box_properties(&original.box_rare);
不是那種型別struct status *。它們屬于struct boxes *.
那么,為什么不申報的功能store_box_properties類似
void store_box_properties(struct boxes *status_pointer)
uj5u.com熱心網友回復:
你的struct status型別
void attempt_volume_exchange_move(void) {
struct status {
struct boxes box_dense, box_rare;
} ...
是函式區域的,如果您將指向它的指標傳遞給另一個函式,則目標內容不能像struct status在該函式中那樣處理。
C 不允許您從不同的函式訪問塊本地定義。如果您struct status在翻譯單元的其他地方重新定義本地,新定義將與塊本地定義不兼容。(雖然您可以利用http://port70.net/~nsz/c/c11/n1570.html#6.2.7漏洞,如果您提供幾乎相同的(相同的成員名稱),您可以在另一個翻譯單元中訪問它、型別、對齊和相同的標簽)結構/聯合定義,我不推薦這種方法,因為它與任意包含的頭檔案不兼容)。
如果你只是想將指標傳遞給original.box_dense, original.box_rare,它們是全域型別struct boxes,那么你可以很容易地做到:
https://gcc.godbolt.org/z/fc33xo7bP
struct boxes {
// Member 1
// Member 2
// Member 3
// ...
// Member N
} box_dense, box_rare;
void store_box_properties(struct boxes *status_pointer);
void attempt_volume_exchange_move(void) {
struct status {
struct boxes box_dense, box_rare;
} original, new;
store_box_properties(&original.box_dense);
store_box_properties(&original.box_rare);
}
void store_box_properties(struct boxes *status_pointer) { // Line where the warning message is given
// Code for store_box_properties
}
也許您打算輸入store_box_propertiesasstruct boxes *而不是的引數struct status *?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363904.html
