В этом руководстве мы научимся передавать объекты в функцию и возвращать объект из функции в программировании на C ++.
В программировании на C ++ мы можем передавать объекты функции так же, как и обычные аргументы.
Пример 1: C ++ передает объекты функции
// C++ program to calculate the average marks of two students #include 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; )
Вывод
Средние оценки = 72
Здесь мы передали два Student
объекта student1 и student2 в качестве аргументов calculateAverage()
функции.

Пример 2: Возвращаемый объект C ++ из функции
#include 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; )
Вывод
Оценка1 = 96,5 Оценка2 = 75

В этой программе мы создали функцию, createStudent()
которая возвращает объект Student
класса.
Мы позвонили createStudent()
из main()
метода.
// Call function student1 = createStudent();
Здесь мы сохраняем объект, возвращаемый createStudent()
методом, в student1.