将私有数据成员作为默认参数传递给该类的公共方法时出错

Error while passing a private data member as default argument to a public method of that class

本文关键字:方法 出错 数据成员 参数传递 默认      更新时间:2023-10-16

我认为标题说明了一切。显示的错误MSVS是

非静态成员引用必须相对于特定对象

我的代码:

struct Node
{
Node(size_t id, int length, int size);
size_t id_;
int length_;
std::vector<Node*> children_;
};
class SuffixTree
{
public:
SuffixTree();
void printSuffixes();
void printSuffixes(Node* current = root_);    // ERROR
~SuffixTree();
private:
Node *root_;
};

还有一些类似的方法,我希望用户从main调用这些方法,但由于root_是私有的,我不得不重载所有这些方法,而用户现在调用重载的方法。这些方法的定义简单如下:

void SuffixTree::printSuffixes()
{
printSuffixes(root_);
}

有什么解决方案吗?

编辑:

void SuffixTree::printSuffixes(Node* current)
{
if (current == nullptr)
return;
if (current->length_ == -1)
std::cout << "leaf" << std::endl;
for (size_t i = 0; i < current->children_.size(); ++i)
printSuffixes(current->children_[i]);
}

默认参数有很多限制。

相反,考虑使用nullptr作为默认值:

void SuffixTree::printSuffixes(Node* current = nullptr)
{
if (current == nullptr)
current = root_;
// ...
}