C++指针默认参数

3

我正在编写一个用C++实现后缀树的程序。我试图声明一个没有参数但需要传递指向自身指针的递归函数。

我这样定义它:

public:
    string longestRepeat(Node*);

在头文件中,以及。
string Trie::longestRepeat(Node* start = &nodes[0]){
    string deepest = "";
    for(unsigned int i = 0; i < start->getEdges(); i++){
        string child_deepest = longestRepeat(start->getChild(i));
        if(child_deepest.length() > deepest.length())
            deepest = child_deepest;
    }
    return deepest;
}

在 .cpp 文件中,node 是一个先前声明的数据结构。
然而,在主函数中简单调用 trie.longestRepeat() 会导致错误“没有匹配的函数调用 Trie::longestRepeat()。候选项期望 1 个参数,但提供了 0 个”。
2个回答

4

如果你将默认参数放在第二个声明(即定义)中,那么只有调用该第二个声明的函数才会使用该默认参数。因此,你需要在声明(头文件中)中放置默认参数。

struct Trie {
    std::string longestRepeat(Node*);
};

int main() {
    Trie{}.longestRepeat(); // Error
}

std::string Trie::longestRepeat(Node *p = &nodes[0]) { }

void g() {
    Trie{}.longestRepeat(); // Ok
}

但是你应该创建一个公共版本的longestRepeat,它调用一个带有&nodes[0]参数的私有/受保护版本:
struct Trie {
    std::string longestRepeat() { // No arguments
        longestRepeat_(&nodes[0]);
    }
private:
    std::string longestRepeat_(Node *); // Real implementation
};

谢谢。但是现在我收到一个错误信息,它声称longestRepeat()过于雄心壮志;因为某种原因它不能在主函数中进行选择。 - Luke Collins
@LukeCollins 你是在尝试第一段还是第二段代码片段? - Holt
我忘了下划线! - Luke Collins

2

对于成员函数,默认参数 可以在类外定义时声明,但只有能看到该定义的翻译单元才能使用默认参数调用成员函数。

这意味着您可以将 Trie::longestRepeat 的定义移动到头文件中以修复错误。

或者更简单的方法是,在声明中而不是定义中声明默认参数。例如:

// header
public:
    string longestRepeat(Node* start = &nodes[0]);

// implementation
string Trie::longestRepeat(Node* start) {
    ...
}

For a member function of a non-template class, the default arguments are allowed on the out-of-class definition, and are combined with the default arguments provided by the declaration inside the class body.

class C {
    void f(int i = 3);
    void g(int i, int j = 99);
};
void C::f(int i = 3) {         // error: default argument already
}                              // specified in class scope
void C::g(int i = 88, int j) { // OK: in this translation unit,
}                              // C::g can be called with no argument

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接