2014-10-08 4 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 파일에서 포함 할 수 있습니까? 유형 UserIdUserInstance의 선언 범위에 있다고 가정하면

+0

어떤 오류 발생 .c 파일에 포함 할 때지고있다? –

+7

C는 연산자 오버로딩을 지원하지 않으므로 기능을 잃지 않고이 코드를 이식 할 수 없습니다. –

+2

c는 연산자 오버로딩을 지원하지 않습니다. 그래서 불가능합니다. –

답변

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

, 당신이 쓸 수 있어야 :

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에서만 헤더가 필요한 경우) 연산자 오버로드를 삭제하면됩니다. –

+1

**이 정의가 'SomeName'에 대한 one-definition 규칙을 위반하기 때문에이 정의가 한 곳에서 C로 컴파일되고 다른 곳에서 C++로 컴파일되는 프로젝트가 있으면 안됩니다. 그러므로 나는 이것을 전혀하지 않을 것을 제안 할 것이다. –

1

당신이 __cplusplus 조건부 사용하는 경우는 C++ 구조체의 정확한 기능을 얻을 수는 없지만, 당신은 부분을 생략 할 수 있습니다, C 컴파일러는 컴파일되지 않습니다. 당신은 C와 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; 

, 난 당신이 구조체에서 연산자 정의를 제거하고, SomeNameEqualsSomeNameNotEquals 기능을 구현하는 순수 C 인터페이스를 쓰기 좋습니다.