C++學習筆記_6:函數的重載

來源:互聯網
上載者:User
//C++允許功能相近的函數在相同的範圍內以相同函數名聲明,從而形成重載。方便使用,便於記憶。//int add(int x, int y);//float add(float x, float y);形參類型不同//int add(int x, int y);//int add(int x, int y, int z);形參個數不同//重載函數的形參必須不同: 個數不同或類型不同。//編譯器將根據實參和形參的類型及個數的首選來選擇調用哪一個函數。//1. 編譯器不以形參名來區分;//2. 編譯器不以傳回值來區分;//3. 不要將不同功能的函式宣告為重載函數,以免出現調用結果的誤解、混淆。#include<iostream.h>struct complex{double real;double imaginary;};int add(int m, int n){  return m+n; }double add(double x, double y){  return x+y; }complex add(complex c1, complex c2){    complex c;c.real=c1.real+c2.real;c.imaginary=c1.imaginary+c2.imaginary;return c;}int main(void){int m, n;double x, y;complex c1, c2, c3;int add(int m, int n);double add(double x, double y);complex add(complex c1, complex c2);cout<<"Enter two integer: ";cin>>m>>n;cout<<"integer "<<m<<'+'<<n<<"="<<add(m,n)<<endl;cout<<"Enter two real number: ";cin>>x>>y;cout<<"real number "<<x<<'+'<<y<<"= "<<add(x,y)            <<endl;cout<<"Enter the first complex number: ";cin>>c1.real>>c1.imaginary;cout<<"Enter the second complex number: ";cin>>c2.real>>c2.imaginary;c3=add(c1,c2);cout<<"complex number (" <<c1.real<< ','           << c1.imaginary <<")+("<<c2.real<<','           <<c2.imaginary<<")=("<<c3.real<<','           <<c3.imaginary<<")\n";            return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.