class Y 的函数不是 X 的成员,但 class X 是 Y 的朋友

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

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

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

我的 class 声明是这样的:

    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 的朋友 class,但错误仍然存​​在(两个 class 成为彼此的朋友)。

提前致谢。

您误解了 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());
        }
    }

...

};