简体   繁体   中英

How can objects access attributes of the class in which they are contained?

Let's imagine I have a code that simulate the working of a country education system. This country contain Cities , which contain Schools , which contain Classes , which contain Students . I use a global singleton called CountryInformation that all classes ( City , School , Class and Students ) are accessing.

I would like to expand my code to consider several countries. Each country need their own CountryInformation , therefore CountryInformation is not a singleton anymore. I would like that each elements contained in a given Country can access to the countryInformation associated to their country. How can I do that?

A simplified version of the problem is to consider that below is my current code

int info = 3;

class City
{
public:
  void foo(){std::cout << info << std::endl;}
};

class Country
{
public:   
  City city;
  void callFoo(){this->city.foo();}
};

int main()
{
  Country C;
  C.callFoo();
}

and I would now like to have something like

class City
{
public:
  void foo(){std::cout << info << std::endl;}
};

class Country
{
public:   
  City city;
  int info;
  void callFoo(){this->city.foo();}
  Country(int i):info(i){}
};

int main()
{
  std::vector<Country> countries;
  Country C1(0);
  Country C2(0);
  countries.push_back(C1);
  countries.push_back(C2);
  countries[0].callFoo();
  countries[1].callFoo();
}

but the above code does not compile as the City object in a given Country does not have access to the attribute of the Country object.

I have been considering friendship and nested classes but I fail to wrap my head around how to give this access.

EDIT

I would like to avoid the need of every City , School and Student to carry a pointer around. A pointer is typically 4 to 8 bytes and a Student is typically 8 bytes. So, doing so would double the RAM need.

Your classes are not "nested;" one class simply has the other classes as members. City objects can only communicate with Country objects via the public API. However, actual nested classes, or inner classes, are able to access the private variables of the outer class:

class Country
{
  class City
  {
  public:
    City(Country& c) : country(c) {}
    void foo() {
      country.info = 1;
    }
  private:
    Country& country;
  };
  int info;
};

Either way, you will have to explicitly pass the Country object to the City object.

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