简体   繁体   中英

Circular reference of two class objects in C++

Is it possible to achieve this code?

class apple;
class fruit{
    public: int i;
    void set(apple a){
    }
};

class apple{
    public: int j;
    void set(fruit f){
    }
};

I know this leads to error: 'a' has incomplete type. even I interchange classes, It always leads to incomplete type error. I have a question can this be achieved? Iam not sure. any help is greatly apprciated. Thanks

Update

class apple;
class fruit{
    public: int i;
    void set(apple* a);
};

class apple{
    public: int j;
    void set(fruit f){
    }
};
void fruit::set(apple *a){
  apple b = *a;
}

I Guess this workaround works. but is there any other solution?

It's possible, but you need to have method definitions outside of the class:

class apple;

class fruit {
public:
    int i;
    void set(apple a);
};

class apple {
public:
    int j;
    void set(fruit f);
};

void fruit::set(apple a)
{
    i = a.j;
}
void apple::set(fruit f)
{
    j = f.i;
}

Using pointers or references, since only the name needs to be known in that case:

class apple;

class fruit{
    public: 
    int i;
    void set(apple* a); // OK
    void set(apple& a); // Also OK
};

And you need to move the implementation of the function to a place where the definition of apple is known.

You cannot have a circular reference like this. Only possibility is to have a pointer to object used instead of object, as in:

class apple;
class fruit{
    public: int i;
    void set(apple * a){
    }
};

class apple{
    public: int j;
    void set(fruit * f){
    }
};

and manage with de-referenced object within the functions, ie use *f within the implementation of these functions apple::set and fruit::set If you would like to have the object non-modifiable when you pass as a pointer, use as:

class apple;
class fruit{
    public: int i;
    void set(const apple * a){
    }
};

class apple{
    public: int j;
    void set(const fruit * f){
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM