如何正确转发声明一个typedef'd结构

时间:2014-07-28 14:55:49

标签: c visual-c++ struct typedef forward-declaration

我想要实现的目标:我想在typedef'd结构中使用typedef'd函数指针,其中函数指针将结构指针作为参数(即类似于'对象方法'的东西) - 对'对象'的引用。)

我有这个C代码(简化,希望不要过分简化):

typedef struct MYSTRUCT myStruct;

typedef void (*getSomething)(myStruct*);

typedef struct MYSTRUCT {
    getSomething get_something;
};

void get_property() {
    myStruct *structure = NULL;
}

所以我认为我正在做的是:转发声明结构,在函数指针typedef中使用该声明,然后使用typedef'd函数指针声明实际结构。

这段代码用linux上的intel编译器编译(似乎做了预期的事情),但Visual编译器抛出错误:

  

错误C2275:'myStruct':非法使用此类型作为表达式   见myStruct的声明

有没有办法让VC接受我想要的构造?

3 个答案:

答案 0 :(得分:1)

typedef struct MYSTRUCT {
    getSomething get_something;
};

应该是

struct MYSTRUCT {
    getSomething get_something;
};

答案 1 :(得分:0)

struct MYSTRUCT;                  // Forward declare the struct
typedef struct MYSTRUCT myStruct; // define the typedef;

typedef void (*getSomething)(myStruct*);   // use the typedef;

struct MYSTRUCT {                 // define the struct
    getSomething get_something;
};

void get_property() {             // use the typedef again.
    myStruct *structure = NULL;
}

// Warning: I didn't actually compile that, and I'm going from memory.

答案 2 :(得分:0)

对不起。我刚才意识到这不是我的前瞻性声明的问题,而是因为我在实际代码中真正做到的是:

void get_property() {
    some = assignment_statement;
    myStruct *structure = NULL;
}

即。我不小心把我的变量声明+定义放在第一个代码语句下面。确实,我过分简化了我的代码片段。对不起。

相关问题