[C++] 用Xcode來寫C++程式[5] 函數的重載與模板

來源:互聯網
上載者:User

標籤:

用Xcode來寫C++程式[5] 函數的重載與模板

 

此節包括函數重載,隱式函數重載,函數模板,帶參數函數模板

 

函數的重載

#include <iostream>using namespace std;int operate (int a, int b) {    return (a * b);}double operate (double a, double b) {    return (a / b);}int main (){    int x    = 5;    int y    = 2;    double n = 5.0 ;    double m = 2.0;        cout << operate (x,y) << ‘\n‘;    cout << operate (n,m) << ‘\n‘;        return 0;}

列印結果

102.5Program ended with exit code: 0

 

 

 

函數模板

#include <iostream>using namespace std;// 模板template <class T>T sum (T a, T b) {    T result;    result = a + b;    return result;}int main () {    // 值初始化    int i    = 5;    int j    = 6;    int k    = 0;    double f = 2.0, g = 0.5, h;        // 使用模板函數    k = sum<int>(i, j);    h = sum<double>(f, g);        // 列印輸出    cout << k << ‘\n‘;    cout << h << ‘\n‘;        return 0;}

列印結果

302.5Program ended with exit code: 0

 

 

 

模板自動匹配

#include <iostream>using namespace std;template <class T, class U>bool are_equal (T a, U b) {    return (a == b);}int main () {        // 自動模板識別    if (are_equal(10,10.0))        cout << "x and y are equal\n";    else        cout << "x and y are not equal\n";    return 0;}

列印結果

x and y are equalProgram ended with exit code: 0

 

 

 

帶參數的模板

#include <iostream>using namespace std;template <class T, int N>T fixed_multiply (T val) {    return val * N;}int main() {    std::cout << fixed_multiply<int, 2>(10) << ‘\n‘;    std::cout << fixed_multiply<int, 3>(10) << ‘\n‘;}

列印結果

2030Program ended with exit code: 0

 

[C++] 用Xcode來寫C++程式[5] 函數的重載與模板

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.