在本文中,您將學(xué)習(xí)在C ++編程中將對(duì)象傳遞給函數(shù)并從函數(shù)返回對(duì)象。
在C ++編程中,對(duì)象可以通過與結(jié)構(gòu)相似的方式傳遞給函數(shù)。
C ++程序通過將對(duì)象傳遞給函數(shù)來添加兩個(gè)復(fù)數(shù)。
#include <iostream> using namespace std; class Complex { private: int real; int imag; public: Complex(): real(0), imag(0) { } void readData() { cout << "分別輸入實(shí)數(shù)和虛數(shù):"<<endl; cin >> real >> imag; } void addComplexNumbers(Complex comp1, Complex comp2) { // real表示對(duì)象c3的實(shí)際數(shù)據(jù),因?yàn)槭褂么ac3.add(c1,c2);可以調(diào)用此函數(shù); real=comp1.real+comp2.real; // imag代表對(duì)象c3的imag數(shù)據(jù),因?yàn)槭褂么ac3.add(c1,c2);可以調(diào)用此函數(shù) imag=comp1.imag+comp2.imag; } void displaySum() { cout << "Sum = " << real<< "+" << imag << "i"; } }; int main() { Complex c1,c2,c3; c1.readData(); c2.readData(); c3.addComplexNumbers(c1, c2); c3.displaySum(); return 0; }
輸出結(jié)果
分別輸入實(shí)數(shù)和虛數(shù): 2 4 分別輸入實(shí)數(shù)和虛數(shù): -3 4 Sum = -1+8i
在C ++編程中, 對(duì)象可以從函數(shù)返回的方式與結(jié)構(gòu)體相似。
在這個(gè)程序中,將把復(fù)數(shù)(對(duì)象)的和返回給main()函數(shù)并顯示出來。
#include <iostream> using namespace std; class Complex { private: int real; int imag; public: Complex(): real(0), imag(0) { } void readData() { cout << "分別輸入實(shí)數(shù)和虛數(shù):"<<endl; cin >> real >> imag; } Complex addComplexNumbers(Complex comp2) { Complex temp; //real表示對(duì)象c3的實(shí)際數(shù)據(jù),因?yàn)槭褂么ac3.add(c1,c2);可以調(diào)用此函數(shù); temp.real = real+comp2.real; //imag代表對(duì)象c3的imag數(shù)據(jù),因?yàn)槭褂么ac3.add(c1,c2);可以調(diào)用此函數(shù) temp.imag = imag+comp2.imag; return temp; } void displayData() { cout << "Sum = " << real << "+" << imag << "i"; } }; int main() { Complex c1, c2, c3; c1.readData(); c2.readData(); c3 = c1.addComplexNumbers(c2); c3.displayData(); return 0; }