本文介紹了根據(jù)返回值重載一個C++函數(shù)的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我們都知道可以根據(jù)參數(shù)重載一個函數(shù):
We all know that you can overload a function according to the parameters:
int mul(int i, int j) { return i*j; }
std::string mul(char c, int n) { return std::string(n, c); }
可以根據(jù)返回值重載函數(shù)嗎?定義一個函數(shù),根據(jù)返回值的使用方式返回不同的東西:
Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used:
int n = mul(6, 3); // n = 18
std::string s = mul(6, 3); // s = "666"
// Note that both invocations take the exact same parameters (same types)
您可以假設(shè)第一個參數(shù)在 0-9 之間,無需驗證輸入或進(jìn)行任何錯誤處理.
You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.
推薦答案
class mul
{
public:
mul(int p1, int p2)
{
param1 = p1;
param2 = p2;
}
operator int ()
{
return param1 * param2;
}
operator std::string ()
{
return std::string(param2, param1 + '0');
}
private:
int param1;
int param2;
};
不是說我會用那個.
這篇關(guān)于根據(jù)返回值重載一個C++函數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!