简体   繁体   中英

c++: how to access private variable of a class from a function of another class

I have two classes, "cache" and "LRU": Class cache looks something like this:

class cache
{
  private:
    int num_cold;                               //Number of cold misses
    int num_cap;                               //Number of capacity misses
    int num_conf;                               //Number of conflict misses
    int miss;                                   //Number of cache misses
    int hits;                                   //Number of cache hits

  public:
           // methods
}

Also i have a method in class LRU

bool LRU::access (Block block)
{
  for (i = lru.begin(); i != lru.end(); i++)               //If 
  {
    if (i->get_tag() == block.get_tag() && i->get_index() == block.getIndex()) 
    {
      lru.push_back(block);
      lru.erase(i);
      return true;
      //Here i want to add 1 to the value of variable "hits" of class "cache"
    }
  }
}

I want to increment the values of variables in class "cache" in the method "LRU::access". Could someone please tell me how i can do that. Thanks.

Add this to cache :

friend class LRU;

This will let any code in LRU access all private members of cache .

您可以将LRU声明为要缓存的朋友类。

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