c++ - 将私有(private)数据成员作为默认参数传递给该类的公共(public)方法时出错

标签 c++

我认为标题说明了一切。 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/

相关文章:

C++ 与 OpenMP 在 N 体模拟器中给出 -not-a-numbers (nan)

c++ - 有没有可靠的方法可以在没有电子邮件客户端的情况下实现电子邮件功能?

c++ - C++头文件中的静态函数

c++ - 由于 ¦ ¬(货币符号),输入文件无法正确显示

c++ - 在套接字 C/C++ 上发送浮点值

c++ - 隐式转换不适用于 BOOST_STRONG_TYPEDEF 和 BOOST_SPIRIT_DEBUG_NODE

c++ - 如何避免额外的 'extern' 缩进

c++ - 将 "ddd"附加到远程计算机上运行的进程

c++ - 在运行时检查 Windows 是否为 64 位的正确方法? (C++)

c++ - 为什么我的 dev-c++ "can' t 打开输出文件”?