我认为标题说明了一切。 MSVS 显示的错误是
a nonstatic member reference must be relative to a specific object
我的代码:
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_
是私有(private)的,我不得不重载所有这些方法,用户现在调用重载方法代替。这些方法的定义很简单:
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]);
}
最佳答案
Default arguments有很多限制。
相反,考虑使用 nullptr
作为默认值:
void SuffixTree::printSuffixes(Node* current = nullptr)
{
if (current == nullptr)
current = root_;
// ...
}
关于c++ - 将私有(private)数据成员作为默认参数传递给该类的公共(public)方法时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564562/