簡體   English   中英

C:結構少了一個字段。 如何有效聲明/使用它?

[英]C: struct with one less field. How do I declare/use it efficiently?

假設我們有兩個不同的struct ,這些struct具有大多數公共字段,但是有一個或兩個不同的字段或更少的字段。 例如:

typedef struct HobbyNodetag {
    char *name; // hobby name
    struct HobbyNodetag* link; // link to next HobbyNode
    int count; // number of times this hobby was mentioned by user
    // more fields... 
    // but identical type/variable name with MyHobbyList
} HobbyNode; // database of entire hobby node; singly linked list

typedef struct MyHobbyTag{
    char *name; // hobby name
    struct MyHobbyTag* link; // linked to next MyHobbyNode
    // more fields... 
    // but identical type/variable name with EntireHobbyList
} MyHobbyNode; // single person's hobby node; singly linked list

我們是否有更有效/更優雅的編碼實踐來使用以上兩個struct 擁有兩個不同的struct因為它們共享大多數字段,這不是浪費嗎?

更新

我先前的問題是令人誤解的。 上面的示例是該節點並被單鏈接(通過link )。

您可以將所有其他字段(存在於第二個結構中但不存在於第一個結構中)移到結構類型定義的末尾,然后將較小的結構用作較大結構的“基礎”:

struct BaseFoo {
    int count;
    char name[128];
    float value;
};

struct ExtendedFoo {
    struct BaseFoo base;
    struct ExtendedFoo *next;
};

這個解決方案的優點是您可以擁有“多態性”:由於C標准保證內存中的第一個struct成員之前沒有填充,因此可以正常工作:

void print_name(struct BaseFoo *foo)
{
    printf("Count: %d\n", foo->count);
    printf("Name: %s\n", foo->name);
}

struct ExtendedFoo foo = { /* initialize it */ };
print_name((BaseFoo *)&foo);

您可以執行類似的操作,但是我相信這不是您要追求的。

typedef struct myHobbyTag{
    char *name;
    struct myHobbyTag* link; 

} MyHobbyList; 

typedef struct entireHobbytag {
    MyHobbyList commonPart;

    int count;
} EntireHobbyList; 

如果將所有公共字段移到頂部,則可以在C中使用OOP聲明基類和繼承類(在StackOverflow上搜索)。

基本上有兩種方法可以做到這一點。

  1. 聲明一個基類,然后在繼承類(具有更多字段)中,將基類作為成員放在繼承類的頂部。

    struct hobbyLink; //通用鏈接

     typedef struct baseHobbytag { char *name; struct hobbyLink* link; } BaseHobby; typedef struct myHobbyTag{ BaseHobby hobby; int count; // more fields... } HobbyTag; 
  2. 您對所有通用基本成員使用#define,並將該#define放入所有繼承的類中。

     #define BASEHOBBY_MEMBERS \\ char *name; \\ struct hobbyLink* link; // base class typedef struct baseHobbytag { BASEHOBBY_MEMBERS } BaseHobby; // Inherit basehobby typedef struct myHobbyTag{ BASEHOBBY_MEMBERS int count; // more fields... } HobbyTag; 

暫無
暫無

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

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