重载参数列表中与原始函数仅 "const" 不同的函数
overloading a function which differs from the original only by "const" in parameter list
我有一个关于重载函数的问题,只有 "const" 不同。例如,如果有一个函数 A,它是按引用传递的,则可以通过按引用传递给常量来重载它。但是,什么时候调用第一个,什么时候调用第二个?
谢谢!
我猜你的意思是这样的
void A(int& arg)
{
...
}
void A(const int& arg)
{
...
}
然后就可以使用类似
的函数了
int i = 5;
A(i); // will call `A(int&)`
A(5); // will call `A(const int&)`
const int ci = 5;
A(ci); // will call `A(const int&)`
绝对可以。
void foo(int& ) { std::cout << "ref\n"; }
void foo(const int& ) { std::cout << "cref\n"; }
如果您传递类型 int
的非常量左值,将调用第一个。在任何其他情况下都会调用第二个。
int i = 4;
const int ci = i;
foo(4); // cref
foo(i); // ref
foo(ci); // cref
foo(1L); // cref
struct X {
operator int() { return 42; }
};
foo(X{}); // cref
我有一个关于重载函数的问题,只有 "const" 不同。例如,如果有一个函数 A,它是按引用传递的,则可以通过按引用传递给常量来重载它。但是,什么时候调用第一个,什么时候调用第二个? 谢谢!
我猜你的意思是这样的
void A(int& arg)
{
...
}
void A(const int& arg)
{
...
}
然后就可以使用类似
的函数了int i = 5;
A(i); // will call `A(int&)`
A(5); // will call `A(const int&)`
const int ci = 5;
A(ci); // will call `A(const int&)`
绝对可以。
void foo(int& ) { std::cout << "ref\n"; }
void foo(const int& ) { std::cout << "cref\n"; }
如果您传递类型 int
的非常量左值,将调用第一个。在任何其他情况下都会调用第二个。
int i = 4;
const int ci = i;
foo(4); // cref
foo(i); // ref
foo(ci); // cref
foo(1L); // cref
struct X {
operator int() { return 42; }
};
foo(X{}); // cref