如何从 C++ 函数传递和返回对象?

在C++编程中,我们可以像传递内置数据类型一样,将对象传递给函数

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

// C++ program to calculate the average marks of two students

#include <iostream>
using namespace std;

class Student {

   public:
    double marks;

    // constructor to initialize marks
    Student(double m)
      : marks{m} {
    }
};

// function that has objects as parameters
double average_marks(Student s1, Student s2) {

    // return the average of marks of s1 and s2 
    return (s1.marks + s2.marks)/2 ;
}

int main() {
    Student student1(88.0), student2(56.0);

  // pass the objects as arguments
   cout << "Average Marks = " << average_marks(student1, student2) << "\n";

    return 0;
}

输出

Average Marks = 72

在这里,我们将两个Student对象student1student2作为参数传递给了calculateAverage()函数。

C++ Pass Objects to Function
C++中将对象传递给函数

示例 2:C++从函数返回对象

#include <iostream>
using namespace std;

class Student {
   public:
    double marks1, marks2;
};

// function that returns object of Student
Student createStudent() {
    Student student;

    // Initialize member variables of Student
    student.marks1 = 96.5;
    student.marks2 = 75.0;

    // print member variables of Student
    cout << "Marks 1 = " << student.marks1 << endl;
    cout << "Marks 2 = " << student.marks2 << endl;

    return student;
}

int main() {
    Student student1;

    // Call function
    student1 = createStudent();

    return 0;
}

输出

Marks1 = 96.5
Marks2 = 75
C++ Return Object from Function
C++中从函数返回对象

在此程序中,我们创建了一个函数createStudent(),该函数返回一个Student类的对象。

我们已从main()方法调用了createStudent()

// Call function
student1 = createStudent();

在这里,我们将createStudent()方法返回的对象存储在student1中。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战