日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

10.1 分别通过函数和重载运算符来实现复数相加

發布時間:2025/4/16 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 10.1 分别通过函数和重载运算符来实现复数相加 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#include <iostream> using namespace std; class Complex { public:Complex(){real=0;imag=0;}Complex(int r,int i){real=r;imag=i;}Complex complex_add(Complex &c2)//復數相加函數{Complex c;c.real=real+c2.real;c.imag=imag+c2.imag;return c;}void display(); private:int real,imag; }; void Complex::display() {cout<<'('<<real<<','<<imag<<"i)"<<endl; } int main() {Complex c1(3,4),c2(-5,10),c3;c3=c1.complex_add(c2);cout<<"c1=";c1.display();cout<<"c2=";c2.display();cout<<"c1+c2=";c3.display();return 0; }

#include <iostream> using namespace std; class Complex { public:Complex(){real=0;imag=0;}Complex(int r,int i){real=r;imag=i;}Complex operator+(Complex &c2)//重載運算符的函數,用于復數相加{Complex c;c.real=real+c2.real;c.imag=imag+c2.imag;return c;}void display(); private:int real,imag; }; void Complex::display() {cout<<'('<<real<<','<<imag<<"i)"<<endl; } int main() {Complex c1(3,4),c2(-5,10),c3;c3=c1+c2;//系統自動調用c1.operator+(c2)來完成c1+c2;cout<<"c1=";c1.display();cout<<"c2=";c2.display();cout<<"c1+c2=";c3.display();return 0; } 重載運算符函數的一般格式如下: 函數類型 operator運算符名稱(參數列表) {對運算符重載的處理}


總結

以上是生活随笔為你收集整理的10.1 分别通过函数和重载运算符来实现复数相加的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。