【问题标题】:Problem with friend function and aggregation in c++c++中友元函数和聚合的问题
【发布时间】: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-&gt;num_children n-&gt;pos 仍然是私有的,我无法通过此函数访问它们。

问题出在哪里?

有没有办法从operator&lt;&lt;函数访问节点的私有成员?

【问题讨论】:

  • 有两种解决方案:1)让operator&lt;&lt;tree_pos_vector 成为node 的朋友。 2nd) 为tree_pos_vector 添加一个包装函数,让tree_pos_vector 的朋友访问node 的私人详细信息。我更喜欢:3rd) 使const 函数公开类的私有细节但只读。在这种情况下,输出不需要友谊。 (哦,我必须承认有 三个 解决方案...)
  • 将(私有)成员函数添加到tree_pos_vector,接受node 并返回其num_childrenpos
  • @Scheff'sCat 我想添加第四个;)通过命名空间详细信息中定义的接口(抽象基)访问数据。这些接口将具有私有实现,以确保“普通”客户端不会直接访问方法onlinegdb.com/eYo4VocRx。 (好吧,这是我在玩接口,我喜欢它们,因为它们可以用来建模使用,哪个类可以得到什么)

标签: c++ templates operator-overloading private friend


【解决方案1】:

您应该在类外部为tree_pos_vector 定义operator&lt;&lt;,并且只将声明保留在内部(有关工作示例,请参见here。但请注意,您在问题中给出的代码有我必须在那里修复的其他几个缺陷,我的解决方案可能不是您想要的。总之,尽量不要盲目复制粘贴示例)。

据我所知,这是因为定义在类体内的友元运算符对正常查找不可见,并且只能由 ADL 检测到,但我在 cppreference 上找不到明确提及。 (我刚刚再次搜索检查,发现提到了这个on stackoverflow。如果你对确切的细节感兴趣,你应该从那里开始)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    相关资源
    最近更新 更多