如您所見,我想在邏輯上將表與游標實作分開。另外,我想對用戶隱藏表和游標資訊。但是,這樣做會產生以下編譯錯誤
./table.h:10:1: error: unknown type name 'Cursor'
另一種解決方案是轉發宣告結構或將結構宣告放入頭檔案中。但它們不是很優雅。
或者我只是不知道如何以“更好”的方式使用前向宣告。
有沒有其他方法可以實作我在這里嘗試做的事情?
任何幫助將不勝感激。
游標.h
#ifndef CURSOR_H
#define CURSOR_H
#include "table.h"
typedef struct Cursor_t Cursor; //struct data hiding
//struct Table; //alternative solution: forward declaration
//struct Table* cursor_get_table(Cursor* cursor);
Table* cursor_get_table(Cursor* cursor);
#endif
游標檔案
#include "cursor.h"
typedef struct Cursor_t {
Table* table;
} Cursor;
//struct Table* cursor_get_table(Cursor* cursor) { //alternative solution
Table* cursor_get_table(Cursor* cursor) {
return cursor->table; //warning: incompatible pointer types returning 'Table *'...
}
表.h
#ifndef TABLE_H
#define TABLE_H
#include "cursor.h"
typedef struct Table_t Table; //struct data hiding
//struct Cursor; //alternative solution: forward declaration
//struct Cursor* table_start(Table* table);
Cursor* table_start(Table* table); //error: unknown type name 'Cursor'
#endif
表.c
#include "table.h"
typedef struct Table_t {
} Table;
//struct Cursor* table_start(Table* table) { //alternative solution
Cursor* table_start(Table* table) {
return 0;
}
主檔案
#include <stdio.h>
#include "cursor.h"
#include "table.h"
int main() {
Table* table;
Cursor* cursor;
printf("hello world\n");
return 0;
}
請注意 main.c 只是一個測驗代碼。我不想在這里完成任何有意義的事情。
uj5u.com熱心網友回復:
您的頭檔案中存在回圈依賴關系,因此只有其中一個包含在另一個中,具體取決于您正在編譯的檔案。
兩個頭檔案都需要查看對方型別的前向宣告,因此使用型別創建第三個頭檔案并將其包含在現有頭檔案中。
型別.h
#ifndef TYPES_H
#define TYPES_H
typedef struct Cursor_t Cursor;
typedef struct Table_t Table;
#endif
游標.h
#ifndef CURSOR_H
#define CURSOR_H
#include "types.h"
Table* cursor_get_table(Cursor* cursor);
#endif
表.h:
#ifndef TABLE_H
#define TABLE_H
#include "types.h"
Cursor* table_start(Table* table);
#endif
您的 .c 檔案將具有結構定義,但沒有結構定義,typedef因為它已經存在。
uj5u.com熱心網友回復:
使用指標的前向結構宣告也是一種資料隱藏形式。cursor.c無法訪問Table內部,并包含Cursor定義。
這允許在不重新編譯用法的情況下更改實作(通過 makefile)。
您可能需要僅在 cursor.c 和 table.c 之間的函式,但它甚至可以放在 cursor_table.h 或您喜歡的任何樣式中。存在緊密耦合的“類”。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/383269.html
