类Y的函数不是X的成员,但类X是Y的友元

function of class Y is not a member of X, but class X is a friend of Y

本文关键字:但类 友元 成员 函数      更新时间:2023-10-16

有一个类似的问题,这个函数是一个带参数的操作符重载,这是主要的重点,这只会让我更加困惑。

我只是试图在一个非空Node对象上调用的树类上执行一个短递归函数,以便分别遍历树的子节点。

我的类声明如下:
    template<class T>
    class BTNode {
        template<class I>
        friend class BST;
        T data;
        BTNode<T>* left_;
        BTNode<T>* right_;
    ...
    }
template<class I>
class BST {
    BTNode<I>* root_;
    BTNode<I>* curr_;
    BTNode<I>* parent_;
    int currSize = 0;
public:
    size_t size() const {
        if (root_ == NULL) {
            return currSize;
        }
        else {
            BTNode<I>* left_ = root_->getLeft();
            BTNode<I>* right_ = root_->getRight();
            if (left_ != NULL) 
                currSize += left_->size();
            if (right_ != NULL) 
                currSize += right_->size();
        }
        return currSize;
    }
...
};

当前的错误是:

'size()': is not a member of 'BTNode<I>'

到目前为止,我已经尝试将BTNode设置为BST的朋友类,但错误仍然存在(两个类互为朋友)

您误解了friend声明的作用。说AB的朋友意味着A可以访问Bprotectedprivate成员。例如,它允许A调用Bprivate函数。它不以任何方式扩展AB的接口。

如果我正确理解你想要实现的目标,你应该能够通过让size接受参数来做到这一点:

template<class I>
class BST {
    BTNode<I>* root_;
    BTNode<I>* curr_;
    BTNode<I>* parent_;
public:
    size_t size() const {
        return size_(root_);
    }
private:
    static size_t size_(const BTNode<I> *node) {
        if (node == NULL) {
            return 0;
        }
        else {
            return 1 + size_(node->getLeft()) + size_(node->getRight());
        }
    }
...
};