![](/img/trans.png)
[英]How to declare template member function of template class X as friend of nested class X::Y
[英]function of class Y is not a member of X, but class X is a friend of Y
有一个与此类似的问题,该函数是带有参数的运算符重载,这是主要重点,这只会使我进一步困惑。
我只是试图在非空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
声明的作用。 说A
是B
的朋友,则意味着A
可以访问B
protected
成员和private
成员。 例如,它允许A
调用B
private
函数。 它不会以任何方式扩展A
或B
的接口。
如果我正确理解了您要实现的目标,则可以通过使用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());
}
}
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.