c++ - 将函数定义为静态成员和自由成员之间有什么区别?

标签 c++ overloading

<分区>

考虑以下代码片段:

#include <iostream>

using namespace std;

struct Element {
    void SetVisible(bool) { cout << "Called SetVisible on Element" << endl; }
};

struct ElementQuery {
    ElementQuery(Element * e) : element(e) { }
    Element * Get() const { return element; }
    Element * element;
};

namespace A {

static void SetVisible(ElementQuery const& element, bool show) {
    cout << "Called SetVisible on ElementQuery" << endl;
    SetVisible(element.Get(), show);
}

static void SetVisible(Element * element, bool show) {
    element->SetVisible(show);
}

};

int main() {
    Element * e = new Element();
    ElementQuery q(e);
    A::SetVisible(q, true);
    delete e;
    return 0;
}

运行时,程序因调用 SetVisible(element.GetFirst(), show) 中的无限递归而失败。我认为这是因为函数 SetVisible(Element * element, bool show) 在调用时尚未声明,尽管它更适合重载解析。

但是当我将 namespace A 更改为 struct A 时,重新编译并运行,一切正常。程序向 cout 打印两行并优雅地结束。

我的问题是:为什么第二个调用“看到”了 SetVisible 的第二个声明,这些声明之间有什么区别?

最佳答案

这是因为命名空间是按顺序处理的,并且在 Element 和 ElementQuery 之间存在转换(因为您的构造函数不是显式的)。

修改后的代码

#include <iostream>

using namespace std;

struct Element {
    void SetVisible(bool) { cout << "Called SetVisible on Element" << endl; }
};

struct ElementQuery {
    explicit ElementQuery(Element * e) : element(e) { }
    Element * Get() const { return element; }
    Element * element;
};

namespace A {

static void SetVisible(Element * element, bool show) {
    cout << "Called A::SetVisible on Element" << endl;
    element->SetVisible(show);}

static void SetVisible(ElementQuery const& element, bool show) {
    cout << "Called A::SetVisible on ElementQuery" << endl;
    SetVisible(element.Get(), show);
}

};

int main() {
    Element * e = new Element();
    ElementQuery q(e);
    A::SetVisible(q, true);
    delete e;
    return 0;
}

关于c++ - 将函数定义为静态成员和自由成员之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11241619/

相关文章:

c++ - 将参数移动到 std::thread 中?

c++ - PostThreadMessage & 发送消息

perl - 如何在 Perl 标量上调用方法?

c++ - 在 C++ 的 gdb 中修改数组元素的值

c++ - 如何将 int 转换为 VARTYPE?

c++ - float 减法返回不正确的值

java - 有没有一种方法可以在不进行强制转换的情况下解决不明确的方法调用?

c++ - 为什么函数重载不会导致歧义错误? (c++)

php - PHP 中的构造函数重载

c - C中的函数重载