跳到主要内容

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

提示
  1. 传递对象给函数:在C++中,可以像传递普通参数一样将对象传递给函数。例如,calculateAverage()函数接受两个Student类的对象作为参数,并计算它们的平均分。
  2. 从函数返回对象:C++程序中的函数可以返回类的对象。例如,createStudent()函数创建并初始化一个Student类的对象,并将此对象返回给调用它的函数。
  3. 对象初始化和赋值:在传递和返回对象时,可以通过构造函数初始化对象的成员变量,并在函数内部修改这些变量。这些变化可以在函数返回对象时保留并在主函数中访问。

在C++编程中,我们可以以类似于传递常规参数的方式将对象传递给函数。

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

// C++ 程序计算两个学生的平均成绩

#include <iostream>
using namespace std;

class Student {

public:
double marks;

// 构造函数初始化分数
Student(double m) {
marks = m;
}
};

// 有对象作为参数的函数
void calculateAverage(Student s1, Student s2) {

// 计算 s1 和 s2 分数的平均值
double average = (s1.marks + s2.marks) / 2;

cout << "平均分数 = " << average << endl;

}

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

// 将对象作为参数传递
calculateAverage(student1, student2);

return 0;
}

输出

平均分数 = 72

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

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

#include <iostream>
using namespace std;

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

// 返回 Student 对象的函数
Student createStudent() {
Student student;

// 初始化 Student 的成员变量
student.marks1 = 96.5;
student.marks2 = 75.0;

// 打印 Student 的成员变量
cout << "成绩 1 = " << student.marks1 << endl;
cout << "成绩 2 = " << student.marks2 << endl;

return student;
}

int main() {
Student student1;

// 调用函数
student1 = createStudent();

return 0;
}

输出

成绩1 = 96.5
成绩2 = 75

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

我们在 main() 方法中调用了 createStudent()

// 调用函数
student1 = createStudent();

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