简体   繁体   中英

Accessing member variables of recursive classes

class B;
class A
{
public:
    string name;
    B* box;
};

class B
{
public:
    string name;
    A appple;
};


int main()
{
  A theobjectA;
  theobjectA.name  = "lalal";
  B* bbb = new B;
  theobjectA.box = bbb;
  bbb->name = "asasasdd";

  cout<<theobjectA.name<<*(theobjectA.box);
}

I wanted to know why I am not able to access the box value in class A?It does not allow to dereference the pointer.Moreover,I am unable to understand how would I be able to use this mutually recursive classes.

You are accessing it. Your program fails since you're trying to send the object of class B type to operator << of object cout . Naturally, the general operator << doesn't know what to do with such input. If you want to print the name member of your object, you should send it to operator << instead of the entire object: theobjectA.box->name .

Edit : Thanks to @AlgirdasPreidžius for noticing a typo.

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