类Y的函数不是X的成员,但类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());
}
}
...
};
相关文章:
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何在嵌套类中正确使用友元声明?
- 继承和友元函数,从基类访问受保护的成员
- 将子类方法声明为基类的友元
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- 尝试重载模板类友元<<运算符时出错
- 声明一个模板函数,将模板类友元的两个对象(仅)带到这两个专用化
- 在子类函数中访问超类友元的受保护数据成员
- c++11 std::thread 和类友元函数之间的交互
- 模板类友元运算符成员函数
- C++模板类友元运算符重载
- 为什么我的类友元函数无法访问具有命名空间的受保护成员?
- 类成员函数调用类友元函数(都是同一个类)可能
- 函数在类作用域之外声明,但不是友元.这是怎么回事
- 类Y的函数不是X的成员,但类X是Y的友元