static和const如何解决模糊函数调用?

问题描述 投票:1回答:1

我目前正在尝试理解函数调用的概念,并注意到你可以编写可怕的代码,但仍然可以通过滥用隐式转换,const和静态来使其工作。

现在我想了解为什么,特别是如何工作。例如,下面是我用于测试的代码段。

标有(1)的行需要a_const需要它的const修饰符,并且有一个static函数需要或多或少的适当参数。删除这两个中的任何一个都会导致编译错误。那么这是如何工作的呢?

#include <iostream>

struct A {

static void func(const int a, int b) {
    std::cout << "A-1"<<std::endl;
}
void func(const int a, float b) {
    std::cout << "A0"<<std::endl;
}
void func(double a, float b) {
    std::cout << "A1"<<std::endl;
}
void func(unsigned int a, char b) {
    std::cout << "A2"<<std::endl;
}
void func(float a, int b) {
    std::cout << "A3"<<std::endl;
}
};

int main() {
const A a_const;
A a;
a_const.func(1.f,1.f); // (1)
// a.func(1.f,1.f);    // (2)
return 0;
}
c++ static const implicit-conversion function-call
1个回答
0
投票
a.func(1.f,1.f);

这是一个含糊不清的电话,因为所有A::func匹配和没有比另一个更好的匹配。


a_const.func(1.f,1.f);

不是一个模棱两可的调用,因为a_const是const限定的,所有非const A::func都不匹配。重载集只剩下static成员函数。

© www.soinside.com 2019 - 2024. All rights reserved.