原文: https://www.programiz.com/cpp-programming/pass-return-object-function

在本文中,您将学习在 C++ 编程中将对象传递给函数并从函数返回对象。

在 C++ 编程中,对象可以与结构相似的方式传递给函数。


如何将对象传递给函数?

如何通过 C   中的函数传递和返回对象? - 图1


示例 1:将对象传递给函数

C++ 程序,通过将对象传递给函数来加两个复数。

  1. #include <iostream>
  2. using namespace std;
  3. class Complex
  4. {
  5. private:
  6. int real;
  7. int imag;
  8. public:
  9. Complex(): real(0), imag(0) { }
  10. void readData()
  11. {
  12. cout << "Enter real and imaginary number respectively:"<<endl;
  13. cin >> real >> imag;
  14. }
  15. void addComplexNumbers(Complex comp1, Complex comp2)
  16. {
  17. // real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
  18. real=comp1.real+comp2.real;
  19. // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
  20. imag=comp1.imag+comp2.imag;
  21. }
  22. void displaySum()
  23. {
  24. cout << "Sum = " << real<< "+" << imag << "i";
  25. }
  26. };
  27. int main()
  28. {
  29. Complex c1,c2,c3;
  30. c1.readData();
  31. c2.readData();
  32. c3.addComplexNumbers(c1, c2);
  33. c3.displaySum();
  34. return 0;
  35. }

输出

  1. Enter real and imaginary number respectively:
  2. 2
  3. 4
  4. Enter real and imaginary number respectively:
  5. -3
  6. 4
  7. Sum = -1+8i

如何从函数返回对象?

在 C++ 编程中,可以通过与结构类似的方式从函数中返回对象

如何通过 C   中的函数传递和返回对象? - 图2


示例 2:从函数传递和返回对象

在该程序中,复数(对象)的总和返回到main()函数并显示。

  1. #include <iostream>
  2. using namespace std;
  3. class Complex
  4. {
  5. private:
  6. int real;
  7. int imag;
  8. public:
  9. Complex(): real(0), imag(0) { }
  10. void readData()
  11. {
  12. cout << "Enter real and imaginary number respectively:"<<endl;
  13. cin >> real >> imag;
  14. }
  15. Complex addComplexNumbers(Complex comp2)
  16. {
  17. Complex temp;
  18. // real represents the real data of object c3 because this function is called using code c3.add(c1,c2);
  19. temp.real = real+comp2.real;
  20. // imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2);
  21. temp.imag = imag+comp2.imag;
  22. return temp;
  23. }
  24. void displayData()
  25. {
  26. cout << "Sum = " << real << "+" << imag << "i";
  27. }
  28. };
  29. int main()
  30. {
  31. Complex c1, c2, c3;
  32. c1.readData();
  33. c2.readData();
  34. c3 = c1.addComplexNumbers(c2);
  35. c3.displayData();
  36. return 0;
  37. }