[英]Function overloading resolution with const
考慮一下
#include <iostream>
class A
{
public:
void fun(int x) const
{
std::cout<<"int x"<<std::endl;
}
void fun(const int x)
{
std::cout<<"const int x"<<std::endl;
}
void fun(int &x)
{
std::cout<<"int &x"<<std::endl;
}
void fun(const int &x)
{
std::cout<<"const int &x"<<std::endl;
}
};
int main()
{
A obj;
int a = 10;
const int b = 10;
int& ref = a;
const int& ref1 = b;
obj.fun(a);
obj.fun(b);
obj.fun(ref);
obj.fun(ref1);
return 0;
}
編譯時會產生歧義,但由於fun(const int x)都沒有說出歧義,但是刪除它會使代碼正確編譯
當我們使參數const ex-un(const int&x)和函數本身為const ex-fun(int x)const而重載解析時,它有什么區別?
嘗試各種組合還有更多的疑問,因此歡迎使用任何一般性的解釋const的作用,同時歡迎重載解析
聲明時將忽略頂級const,因此fun(const int x)
與fun(int x)
。
當然,它將與ref版本沖突並且幾乎沒有任何意義。 如果您尋找右值,請添加fun(int &&x)
,盡管它通常與用戶定義類型一起使用
()之后的const限定對象實例-this指針。 在使用const A obj
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.