C++ 函数传递和返回对象

来源:这里教程网 时间:2026-02-16 16:05:02 作者:

在本教程中,我们将了解如何将对象作为参数传递给函数以及如何从函数返回对象。

将对象传递给函数

可以将对象传递给函数,就像我们将结构传递给函数一样。在A类中,我们有一个函数disp(),我们在其中传递类A的对象。类似地,我们可以将一个类的对象传递给不同类的函数。

#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;}

输出:

100A

从函数返回对象

在这个例子中,我们有两个函数,函数input()返回Student对象,disp()将Student对象作为参数。

#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;}

输出:

Name: NeganId: 1001Age: 29

相关推荐