با عرض سلام و وقت بخیر خدمت کاربران سایت پی وی لرن ، با یکی دیگر از جلسات دوره کامل آموزش ++C در خدمت شما دوستان هستیم . در بخش قبلی با سازنده ها در ++C آشنا شدید، در این جلسه قصد داریم به آموزش ارسال اشیا به تابع در ++C و اشیا به عنوان مقدار برگشتی تابع بپردازیم.
اشیا در ++C می توانند مانند ساختمان ها به توابع ارسال شوند.
در برنامه زیر دو عدد مختلط را با استفاده از ارسال شی به تابع جمع می زنیم:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <iostream> using namespace std; class Complex { private: int real; int imag; public: Complex(): real(0), imag(0) { } void readData() { cout << "Enter real and imaginary number respectively:"<<endl; cin >> real >> imag; } void addComplexNumbers(Complex comp1, Complex comp2) { // real represents the real data of object c3 because this function is called using code c3.add(c1,c2); real=comp1.real+comp2.real; // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2); 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; } |
خروجی به شکل زیر می باشد:
1 2 3 4 5 6 7 | Enter real and imaginary number respectively: 2 4 Enter real and imaginary number respectively: -3 4 Sum = -1+8i |
در این برنامه جمع دو عدد مختلط به تابع main بر گردانده و نمایش داده می شود:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #include <iostream> using namespace std; class Complex { private: int real; int imag; public: Complex(): real(0), imag(0) { } void readData() { cout << "Enter real and imaginary number respectively:"<<endl; cin >> real >> imag; } Complex addComplexNumbers(Complex comp2) { Complex temp; // real represents the real data of object c3 because this function is called using code c3.add(c1,c2); temp.real = real+comp2.real; // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2); 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; } |
خروجی مانند مثال قبل است.
جلسه ارسال اشیا به تابع در ++C نیز به پایان رسید.
در جلسه بعد به آموزش سربارگذاری عملگر ها در ++C خواهیم پرداخت. با ما همراه باشید.
همچنین می توانید نظرات و سوالات خود را از طریق بخش نظرات سایت با ما در میان بگذارید.
امیرحسین
چرا همش با اعداد کار میکنید یک هم تو مثال ها با رشته کار کنید
پی وی لرن
سلام
در آپدیت جدید اضافه خواهیم کرد.