问题描述
标题可能有点误导。我有以下问题:我有一个由树叶和内部节点组成的树。用户应该能够在树中存储任何信息和,树具有一些方法,它们获得一组用户定义的值,并且需要在常量时间(不是摊销)访问相应的树叶。
The title might be a bit misleading. I have the following problem: I have a tree consisting of leaves and internal nodes. The user should be able to store any information in the leaves and the tree has some methods which get a set of user-defined values and need to access the corresponding leaves in constant time (not amortized).
我想出了以下想法,但它不工作,因为不幸的是我无法访问嵌套类的私有成员:用户创建树和也为每个叶子一个 UserElement
的实例,它包含相应叶的user_defined值。一旦像doSomethingWithTheTree(list>)一样的方法被调用并且树被构建,树创建相应的叶并将它保存在私有字段 leaf
中。每当用户想要调用具有对应于其user_defined值的一些叶的方法时,他/她只需通过给出相应的 UserElement
来调用该方法,并且树可以在固定时间检索相应的树叶。
I came up with the following idea but it does not work because unfortunately I cannot access private members of a nested class: The user creates the tree and also for each leaf an instance of UserElement
which contains the user_defined value for the corresponding leaf. Once a method like doSomethingWithTheTree(list>) is called and the tree is built, the tree creates the corresponding leaves and saves it in the private field leaf
. Whenever the user wants to call a method with some of the leaves corresponding to its user_defined values, he/she just has to call the method by giving the corresponding UserElement
s and the tree can retrieve the corresponding leaves in constant time.
class Tree {
public:
template <typename T>
class UserElement {
private:
T user_value;
tree_node* leaf; // this has to be private for
// everyone outside the class `Tree`
public:
T getInf() {
return user_value;
}
void setInf(T i) {
user_value = i;
}
};
void doSomethingWithTheTree(list<UserElement<T>> elements) {
...
// I want to be able to access elem.leaf for all elements
}
}
推荐答案
一个嵌套类(在另一个类中声明),而不是(继承自其超类)。
Technically, that's a nested class (declared within another class), not a subclass (which inherits from its superclass).
您可以允许Tree类通过将其作为朋友访问其私有:
You can allow the Tree class to access its privates by making it a friend:
class UserElement {
friend class Tree;
// ...
};
或者,为了更好的封装,你可以限制只访问需要它的成员函数,虽然由于需要按正确的顺序声明事物,它有点乱。
or, for better encapsulation, you could restrict access only to the member function(s) that need it, although it gets a bit messy due to the need to declare things in the right order:
class Tree {
public:
// Declare this so we can declare the function
template <typename T> class UserElement;
// Declare this before defining `UserElement` so we can use it
// in the friend declaration
template <typename T>
void doSomethingWithTheTree(list<UserElement<T>> elements) {
elements.front().leaf;
}
template <typename T>
class UserElement {
// Finally, we can declare it a friend.
friend void Tree::doSomethingWithTheTree<T>(list<UserElement<T>>);
// ...
};
};
这篇关于C ++访问嵌套类的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!