C++:如何从另一个类的函数访问类的私有变量

问题描述:

我有两个班,“缓存”和“LRU”: 级缓存看起来是这样的:C++:如何从另一个类的函数访问类的私有变量

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 
} 

我也有类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" 
    } 
    } 
} 

我想增加方法“LRU :: access”中类“缓存”中变量的值。 有人能告诉我我该怎么做。 谢谢。

+0

最简单的答案是公共设置功能hit..or public increment_hit函数 – sethi

+0

LRU如何访问缓存对象? –

一下添加到cache

friend class LRU; 

这将让任何代码LRU访问cache所有私有成员。

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