【发布时间】:2021-11-20 05:57:16
【问题描述】:
我正在为一棵树编写一个简单的数据结构。
我有这些课程:
//declaration of tree_pos_vector
template<class T>
class tree_pos_vector;
template<class T>
class node{
private:
int pos;
int num_children;
/*other member and function
...
*/
public:
/*other function
....
*/
template<class W> friend class tree_pos_vector;
friend std::ostream& operator<<(std::ostream &os,tree_pos_vector<T>& _tree);
}
template<class T>
class tree_pos_vector{
private:
std::vector<node<T>*> vec_node;
/*other member and function
...
*/
public:
/*other function
...
*/
friend std::ostream& operator<<(std::ostream &os,tree_pos_vector<T>& _tree){
for(auto &n: _tree.vec_node){
for(int i=0;i < n->num_children; i++){
os<< "( "<<*n<<","<< vec_node[n->pos*degree+i] << ")\n";
}
}
}
}
问题是成员 n->num_children 和 n->pos 仍然是私有的,我无法通过此函数访问它们。
问题出在哪里?
有没有办法从operator<<函数访问节点的私有成员?
【问题讨论】:
-
有两种解决方案:1)让
operator<<为tree_pos_vector成为node的朋友。 2nd) 为tree_pos_vector添加一个包装函数,让tree_pos_vector的朋友访问node的私人详细信息。我更喜欢:3rd) 使const函数公开类的私有细节但只读。在这种情况下,输出不需要友谊。 (哦,我必须承认有 三个 解决方案...) -
将(私有)成员函数添加到
tree_pos_vector,接受node并返回其num_children和pos。 -
@Scheff'sCat 我想添加第四个;)通过命名空间详细信息中定义的接口(抽象基)访问数据。这些接口将具有私有实现,以确保“普通”客户端不会直接访问方法onlinegdb.com/eYo4VocRx。 (好吧,这是我在玩接口,我喜欢它们,因为它们可以用来建模使用,哪个类可以得到什么)
标签: c++ templates operator-overloading private friend