如何调用非常量重载

How to call a non-const overload?

本文关键字:非常 常量 重载 调用 何调用      更新时间:2023-10-16

void func(const int& i)void func(int& i)之间有什么区别。如果const在顶级被截断,是否有可能调用第二个重载?为什么首选const重载?以下将始终选择第一个过载:

func(42);
func(int{42});
int i = 42;
func(i);
int &j = i;
func(j);
func(i + 1);

哎呀,我明白我现在的问题是什么了。我在两个函数中都键入了cout << "constn",所以看起来它总是调用第一个重载。对不起,伙计们。

const是对自己和其他开发人员的一个提示,即您不打算修改观察到的对象。如果参数为const:,则选择const重载

#include <iostream>
void f(const int&)
{
    std::cout << "f(const int&)n";
}
void f(int&)
{
    std::cout << "f(int&)n";
}
int main()
{
    int a = 0;
    const int b = 0;
    int& c = a;
    const int& d = a;
    f(a);
    f(b);
    f(c);
    f(d);
}

这将输出

f(int&)
f(const int&)
f(int&)
f(const int&)

请参阅此演示。

正如您所看到的,它并不总是const过载。

void func(const int& i)void func(int& i)之间有什么区别。

void func(const int& i)void func(int& i)之间的区别在于,在第一个函数中不能更改i,而在第二个函数中可以更改。

甚至可以调用第二个过载吗?

如果参数不是const,则会选择第二个函数。

为什么首选const过载?

这取决于情况。如果计划更改const的值,则不能使用它。当您希望确保不会意外或有意地更改变量时,应该使用const。看看这篇文章:在C++中尽可能使用const?了解更多信息。