Kā nodot un atgriezt objektu no C ++ funkcijām?

Šajā apmācībā mēs iemācīsimies objektus nodot funkcijai un atgriezt objektu no funkcijas C ++ programmēšanā.

Programmējot C ++, mēs varam objektus nodot funkcijai līdzīgi kā regulāru argumentu nodošanu.

1. piemērs: C ++ nodod objektus funkcijai

 // 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; )

Rezultāts

 Vidējās atzīmes = 72

Šeit mēs esam nodevuši divus Studentobjektus students1 un students2 kā argumentus calculateAverage()funkcijai.

Ievadiet objektus darbībai C ++

2. piemērs: C ++ objekta atgriešana no funkcijas

 #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; )

Rezultāts

 Atzīmes1 = 96,5 Atzīmes2 = 75
Atgrieziet objektu no funkcijas C ++

Šajā programmā mēs esam izveidojuši funkciju, createStudent()kas atgriež Studentklases objektu .

Mēs esam piezvanījuši createStudent()no main()metodes.

 // Call function student1 = createStudent();

Šeit mēs createStudent()glabājam priekšmetā, kuru ar metodi atgrieza students1.

Interesanti raksti...