🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 从 C++ 中的函数传递和返回对象 > 原文: [https://beginnersbook.com/2017/09/cpp-pass-and-return-object-from-a-function/](https://beginnersbook.com/2017/09/cpp-pass-and-return-object-from-a-function/) 在本教程中,我们将了解如何将对象作为参数传递给函数以及如何从函数返回对象。 ## 将对象传递给函数 可以将对象传递给函数,就像我们[将结构传递给函数](https://beginnersbook.com/2017/09/cpp-structure-and-function/)一样。在`A`类中,我们有一个函数`disp()`,我们在其中传递类`A`的对象。类似地,我们可以将一个类的对象传递给不同类的函数。 ```cpp #include <iostream> using namespace std; class A { public: int n=100; char ch='A'; void disp(A a){ cout<<a.n<<endl; cout<<a.ch<<endl; } }; int main() { A obj; obj.disp(obj); return 0; } ``` **输出:** ```cpp 100 A ``` ## 从函数返回对象 在这个例子中,我们有两个函数,函数`input()`返回`Student`对象,`disp()`将`Student`对象作为参数。 ```cpp #include <iostream> using namespace std; class Student { public: int stuId; int stuAge; string stuName; /* In this function we are returning the * Student object. */ Student input(int n, int a, string s){ Student obj; obj.stuId = n; obj.stuAge = a; obj.stuName = s; return obj; } /* In this function we are passing object * as an argument. */ void disp(Student obj){ cout<<"Name: "<<obj.stuName<<endl; cout<<"Id: "<<obj.stuId<<endl; cout<<"Age: "<<obj.stuAge<<endl; } }; int main() { Student s; s = s.input(1001, 29, "Negan"); s.disp(s); return 0; } ``` **输出:** ```cpp Name: Negan Id: 1001 Age: 29 ```