簡體   English   中英

如何組合兩個不同類型的變量?

[英]How to combine two different type variables?

我有兩個函數,正文完全一樣,只是參數不同:

int setCustomerUser(struct userCustomer *user, struct profile *data) {
        user->type = data->type;
        // ....  A
}

int setAdminUser(struct userAdmin *user, struct profile *data) {
        user->type = data->type;
        // ....  B
}

AB是一樣的。

userCustomeruserAdmin基本相同,只是有些不同。

struct userCustomer {
    int type;
    char *name;
    char *mail;

    int gender;
    char *address;
    int point;
    // ....
}

struct userAdmin {
    int type;
    char *name;
    char *mail;

    int dept;
    // ....
}

所以我想把這兩個功能合二為一,像這樣:

int setUser(void *user1, struct profile *data, int userType) {
        if(userType == 0) {
                struct userCustomer *user = (struct userCustomer *)user1;
        } else {
                struct userAdmin *user = (struct userAdmin *)user1;
        }

        user->type = data->type;
        // ...
} 

但正如您所知,C 不是 Python,它不起作用。 我怎樣才能做到這一點?

您可以像這樣在struct使用union成員:

struct user {
    int type;
    char *name;
    char *mail;

    union {
        struct {
            int gender;
            char *address;
            int point;
            // ....
        } customer;

        struct {
            int dept;
            // ....
        } admin;
    };
};

為了區分這兩種類型的值,將“類型”存儲在struct是有意義的。 這就是type已經做到的,即使我會使用enum

您可以像以前一樣訪問公共部分:

user->type = ...;

還有像這樣的特殊部分(但你可能知道這一點):

user->customer.gender = ...;

user->admin.dept = ...;

將公共字段提取到公共結構中。

struct userCommon {
    int type;
    char *name;
    char *mail;
};

struct userCustomer {
    struct userCommon c;
    int gender;
    char *address;
    int point;
};

struct userAdmin {
    struct userCommon c;
    int dept;
};

int userCommon_setType(struct userCommon *c, struct profile *data) {
      c->type = data->type;
      return 62;
}

int userCustomer_setType(struct userCustomer *user, struct profile *data) {
      return userCommon_setType(&user->c, data);
}

int userAdmin_setType(struct userCustomer *user, struct profile *data) {
      return userCommon_setType(&user->c, data);
}

我建議使用帶有 2 個參數的原型是 2 struct 而不是使用userType

這個例子:

int setUser(userCustomer *user, userAdmin *admin, struct profile *data) 
{
    if(user != NULL) 
    {
        user->type = data->type;
    } 
    if (admin != NULL)
    {
        admin->type = data->type;
    }
            // ...
}

暫無
暫無

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

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