2012-11-28 161 views
1

可能重复:
Can inner classes access private variables?比较C++和优先级队列

所以我试图用一个优先级队列,并在此队列的方面,我想定义如果D [i] < D [j],则整数i比另一个整数j“小于”。我怎样才能做到这一点? (d是一个对象的数据成员)

到目前为止,我有

/* This function gets the k nearest neighbors for a user in feature 
* space. These neighbors are stored in a priority queue and then 
* transferred to the array N. */ 
void kNN::getNN() { 
    int r; 
    priority_queue<int, vector<int>, CompareDist> NN; 

    /* Initialize priority queue */ 
    for (r = 0; r < k; r++) { 
     NN.push(r); 
    } 

    /* Look at the furthest of the k users. If current user is closer, 
    * replace the furthest with the current user. */ 
    for (r = k; r < NUM_USERS; r++) { 
     if (NN.top() > r) { 
      NN.pop(); 
      NN.push(r); 
     } 
    } 

    /* Transfer neighbors to an array. */ 
    for (r = 0; r < k; r++) { 
     N[r] = NN.top(); 
     NN.pop(); 
    } 
} 

而且在kNN.hh:

class kNN { 

private: 
    struct CompareDist { 
     bool operator()(int u1, int u2) { 
      if (D[u1] < D[u2]) 
       return true; 
      else 
       return false; 
     } 
    }; 
... 

然而,这是给我的错误

kNN.hh: In member function ‘bool kNN::CompareDist::operator()(int, int)’: 
kNN.hh:29: error: invalid use of nonstatic data member ‘kNN::D’ 

我该怎么办?似乎C++不喜欢它,如果我参考比较器中的特定对象,但我不知道如何解决这个问题,而不用参考D.

谢谢!

+0

这个问题实际上不是关于优先级队列和比较器,但关于内部类如何访问包围类数据成员:HTTP ://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables,http://stackoverflow.com/questions/1604853/nested-class-access-to-enclosing-class-private-data - 成员 – jogojapan

回答

4

您可以传递将D对象引用到CompareDist对象的构造函数中,然后使用operator()中的那个D对象。

在本示例中,我存储了一个指向D的指针。根据D的类型,您可能需要保存D的副本。 (如果D是原始阵列,我的样品中的语法可以被简化。)

struct CompareDist { 
    const DType* pD; 
    CompareDist(const DType& D) : pd(&D) {} 
    bool operator()(int u1, int u2) { 
     return (*pD)[u1] < (*pD)[u2]; 
    } 
}; 

priority_queue<int, vector<int>, CompareDist> NN(CompareDist(D)); 
+0

感谢您的解决方案! –

-1

好了,现在我读过你的问题好,我可以更新的答案:问题是D是包含的kNN实例内的对象,因此它不是static,不能从访问一个静态上下文。

您可以通过使用类中的静态引用d,像

// .h 
class kNN { 
    static Type* current; 
    .. 

    struct CompareDist { 
     bool operator()(int u1, int u2) { 
     if ((*current)[u1] < (*current)[u2]) 
      return true; 
     else 
      return false; 
     } 
    }; 
} 

// .cpp 
Type *kNN::current = NULL; 

void kNN::method() 
{ 
    kNN::current = D; // beforing using the comparator 
    .. 
} 

此外签名应通过const引用使用元素解决的问题,如

bool operator()(const int &u1, const int &u2) 
+0

对不起,我对此很困惑。我什么时候提及集合的特定实例?另外为什么我需要传递一个整数的引用,如果它只是一个整数而不是一个对象? –

+0

我更新了答案以反映您的具体情况,您需要通过引用来避免复制该值。 – Jack

+0

感谢您的帮助! –