Как да предавам и връщам обект от C ++ функции?

В този урок ще се научим да предаваме обекти на функция и да връщаме обект от функция в програмирането на 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()функцията.

Предайте обектите да функционират в C ++

Пример 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
Връщане на обект от функция в C ++

В тази програма създадохме функция, createStudent()която връща обект от Studentклас.

Обадихме се createStudent()от main()метода.

 // Call function student1 = createStudent();

Тук съхраняваме обекта, върнат от createStudent()метода, в student1.

Интересни статии...