2014-10-08 176 views
0

以下內容可以包含在.cpp文件中,編譯器不會抱怨它。C中的結構編譯器問題

typedef struct _SomeName { 
    char NameID[MaxSize]; 
    UserId notUsed; 
    UserInstance instance; 

    bool operator==(const struct _SomeName& rhs) const 
    { 
     return (strncmp(NameID, rhs.NameID, MaxSize) == 0); 
    } 
    bool operator!=(const struct _SomeName& rhs) const { return !(*this == rhs); }; 
} SomeName; 

如何重寫上述內容以便可以從.c文件中包含它?

+0

什麼錯誤,你得到它包括在.c文件時? – 2014-10-08 21:30:54

+7

C不支持運算符重載,所以不能在不丟失功能的情況下移植此代碼。 – 2014-10-08 21:31:05

+2

c不支持運算符重載。所以這是不可能的。 – 2014-10-08 21:31:13

回答

1

到目前爲止發佈的其他解決方案存在的問題是,您不能在混合了C和C++的項目中使用它。我從你的問題的背景猜測你可能想這樣做。如果你這樣做,你可能會得到沉默的未定義行爲,因爲結構可能在不同的翻譯單元中有不同的佈局。

我建議這個版本:

typedef struct 
{ 
    char NameID[MaxSize]; 
    UserId notUsed; 
    UserInstance instance;  
} SomeName; 

#ifdef __cplusplus 
inline bool operator==(SomeName const &lhs, SomeName const &rhs) 
{ 
    return strcmp(lhs.NameID, rhs.NameID) == 0; 
} 
inline bool operator!=(SomeName const &lhs, SomeName const &rhs) 
{ 
    return !operator==(lhs, rhs); 
} 
#endif 
1

假設的類型UserIdUserInstance聲明是在範圍上,你應該能夠這樣寫:

typedef struct _SomeName { 
    char NameID[MaxSize]; 
    UserId notUsed; 
    UserInstance instance; 
#ifdef __cplusplus 
    bool operator==(const struct _SomeName& rhs) const 
    { 
     return (strncmp(NameID, rhs.NameID, MaxSize) == 0); 
    } 
    bool operator!=(const struct _SomeName& rhs) const { return !(*this == rhs); }; 
#endif 
} SomeName; 
+1

這解決了假定的約束,您希望能夠在C++源代碼和C源代碼中包含相同的頭文件,而不會丟失C++端的功能。如果你不需要任何地方的重載操作符(例如,如果你只需要在C中的頭),那麼你可以刪除操作符重載。 – 2014-10-08 21:38:53

+1

請注意,您**不得**有一個項目,其中此定義在一個位置編譯爲C,而在另一個位置編譯爲C++,因爲這違反了「SomeName」的單定義規則。所以我建議不要這樣做。 – 2014-10-08 22:24:23

1

你不能得到的C++結構的確切功能,但如果你使用的__cplusplus條件,你可以省去這些部分,C編譯器不會編譯。

typedef struct _SomeName { 
    char NameID[MaxSize]; 
    UserId notUsed; 
    UserInstance instance; 

    #ifdef __cplusplus 
    bool operator==(const struct _SomeName& rhs) const 
    { 
     return (strncmp(NameID, rhs.NameID, MaxSize) == 0); 
    } 
    bool operator!=(const struct _SomeName& rhs) const { return !(*this == rhs); }; 
    #endif 
} SomeName; 

如果你需要平等的和不等於運營商,在C和C++,我建議你從結構刪除操作的定義,並寫一個純粹的C接口實現SomeNameEqualsSomeNameNotEquals功能。