問題描述
正在試用 stackeroverflow qn 所以它讓我思考為什么不重載該函數(shù),我想出了一個(gè)稍微不同的代碼,但它說該函數(shù)不能被重載.我的問題是為什么?或者有其他方法嗎?
Was tryin out the stackeroverflow qn so it got me thinking why not overload the the function and I came up with a slightly different code but it says the function cannot be overloaded. My question is why? or is there a another way?
#include <iostream>
using std::cout;
class Test {
public:
Test(){ }
int foo (const int) const;
int foo (int );
};
int main ()
{
Test obj;
Test const obj1;
int variable=0;
do{
obj.foo(3); // Call the const function
obj.foo(variable); // Want to make it call the non const function
variable++;
usleep (2000000);
}while(1);
}
int Test::foo(int a)
{
cout<<"NON CONST"<<std::endl;
a++;
return a;
}
int Test::foo (const int a) const
{
cout<<"CONST"<<std::endl;
return a;
}
推薦答案
不能僅基于非指針、非引用類型的常量性進(jìn)行重載.
You can't overload based only on the constness of a non pointer, non reference type.
想想如果你是編譯器.面對(duì)線:
Think for instance if you were the compiler. Faced with the line:
cout <<obj.foo(3);
你會(huì)調(diào)用哪個(gè)函數(shù)?
當(dāng)您按值傳遞時(shí),值會(huì)以任何方式復(fù)制.參數(shù)上的 const 僅與函數(shù)定義相關(guān).
As you are passing by value the value gets copied either way. The const on the argument is only relevant to the function definition.
這篇關(guān)于帶有 const 參數(shù)和重載的函數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!