未声明函数中使用的结构成员

Undeclare structure member used in function?

本文关键字:结构 成员 函数 未声明      更新时间:2023-10-16

我的函数定义不会编译,因为有一个所谓的"未声明"结构成员。上面写着"错误:‘gen’未申报"。但我声明它,甚至在之后初始化它(为了简单起见,我省略了那个部分)。你能明白为什么这个不能编译吗?

我的结构:

typedef struct Parent {     
int gen;            //I DECLARE IT RIGHT HERE!!!
char *name;
struct Parent * next;
child * child;
} parent;

和我的函数:

void findP(parent* x){                  //function findP
    headP = p;
    tempC = headP->child;
    int check = 0;
    while(headP != NULL){
        while(tempC != NULL){
            if (x->name == tempC->name){
                x->gen = gen--;               //HERES WHERE I USE IT
                findP(headP);           //recursion here
                check++;
                break;
            }
            if(check > 0) break;
            tempC = tempC->next;
    }
        if(check > 0) break;
        headP = headP->next;
}
}
x->gen = gen--;

CCD_ 2中的CCD_ 1当然是未声明的。

我认为它应该是指x->gen--;

x->gen = gen--;

x->gen存在。gen?右边的东西是什么?你是指以下内容吗?

x->gen--;

您已声明gen,但已将其声明为structParent的成员。顺便说一句,在结构声明前面不需要typedef

这个问题不明显的原因是您陷入了一个常见的陷阱,即不能使结构/类成员变量不同。许多开发团队采用了一种最佳实践,即用前导m_m或尾随gen0来区分成员变量名。m_似乎是最主要的方式。

struct Parent {     
    int m_gen;            //I DECLARE IT RIGHT HERE!!!
    char * m_name;
    Parent * m_next;
    child * m_child;
};
typedef Parent parent; // if you're hell-bent on having both versions.

现在问题应该变得非常明显:

while(headP != NULL){
    while(tempC != NULL){
        if (x->m_name == tempC->m_name){
            x->m_gen = gen--;               //HERES WHERE I USE IT

gen不是某个事物的成员,它是一个局部变量。如果添加m_前缀

            x->m_gen = m_gen--;               //HERES WHERE I USE IT

很明显,你还没有对右边的m_gen说"member of what",这不是一个成员函数。