C++ 函数使用对象作为参数和返回值
在本教程中,我们将学习在 C++ 编程中将对象传递给函数并从函数返回对象。
在 C++ 编程中,我们可以像传递常规参数一样将对象传递给函数。
示例 1:C++ 将对象传递给函数
下面的 C++ 程序用于计算两个学生的平均成绩。
#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
void calculateAverage(Student s1, Student s2) {
// calculate the average of marks of s1 and s2
double average = (s1.marks + s2.marks) / 2;
cout << "Average Marks = " << average << endl;
}
int main() {
Student student1(88.0), student2(56.0);
// pass the objects as arguments
calculateAverage(student1, student2);
return 0;
}
输出
Average Marks = = 72
在这里,我们 t 通过参数传递了两个 Student
对象 student1
和 student2
给函数 calculateAverage()
。
示例 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;
}
输出
Marks 1 = 96.5
Marks 2 = 75
在这个程序中,我们创建了一个返回 Student
类对象的 createStudent()
函数。
我们在 main()
方法中调用了 createStudent()
函数。
// Call function
student1 = createStudent();
在这里,我们将 createStudent()
方法返回的对象存储在 student1
.