gpt4 book ai didi

c++ - 重载具有其他相同签名的函数以接受引用和 const 引用

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:50 24 4
gpt4 key购买 nike

代码如下:

struct A {};   

void f (A& a) {std::cout << "No const" << std::endl;}

void f (const A& a) {std::cout << "const" << std::endl;}

int main(){
f(A()); // indicated as line A, output will be "const".
}

问题一:

为什么 A 行的输出是“const”,即使 A() 是一个非常量对象?

我认为编译器生成的代码等同于:

const A tempA;
f(tempA);

是这样吗?

问题2),如果两个f函数如下修改,改变对值类型的引用

void f (A a) {std::cout << "No const" << std::endl;} 

void f (const A a) {std::cout << "const" << std::endl;}

以上代码无法编译。编译器给出“函数 f 的重新定义”错误。我可以理解为什么编译器会给出错误,因为可以将 const A 转换为 A ,反之亦然。因此无法在编译时决定。是这样吗?

我还是很好奇c++规范里是不是定义的很好?

最佳答案

Why the line A's output is "const", even though A() is a object without const?

A() 表达式创建了一个不能被非常量左值引用绑定(bind)的临时纯右值,因此 void f (const A& a) 是唯一可行的过载。

I am still very curious that is it very well defined in c++ specification ?

§13.1 [过载]/p3:

— Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called. [ Example:

typedef const int cInt;
int f (int);
int f (const int); // redeclaration of f(int)
int f (int) { /* ... */ } // definition of f(int)
int f (cInt) { /* ... */ } // error: redefinition of f(int)

end example ]

Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations. In particular, for any type T, “pointer to T,” “pointer to const T,” and “pointer to volatile T” are considered distinct parameter types, as are “reference to T,” “reference to const T,” and “reference to volatile T.”

对于 Aconst A 类型的参数,当由任何可转换为 A 的参数初始化时,相同的转换序列适用,编译器永远不会能够在两者之间进行选择。

A&const A& 类型的参数可以有不同的表达式,以便编译器可以选择更好的转换顺序或从候选集中排除任何候选。

关于c++ - 重载具有其他相同签名的函数以接受引用和 const 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27398049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com