Come passare e restituire un oggetto dalle funzioni C ++?

In questo tutorial impareremo a passare oggetti a una funzione e restituiremo un oggetto da una funzione nella programmazione C ++.

Nella programmazione C ++, possiamo passare oggetti a una funzione in modo simile al passaggio di argomenti regolari.

Esempio 1: C ++ passa gli oggetti alla funzione

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

Produzione

 Punteggio medio = 72

Qui, abbiamo passato due Studentoggetti student1 e student2 come argomenti alla calculateAverage()funzione.

Passa gli oggetti alla funzione in C ++

Esempio 2: oggetto restituito in C ++ da una funzione

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

Produzione

 Voti1 = 96,5 Marks2 = 75
Restituisce l'oggetto dalla funzione in C ++

In questo programma abbiamo creato una funzione createStudent()che restituisce un oggetto di Studentclasse.

Abbiamo chiamato createStudent()dal main()metodo.

 // Call function student1 = createStudent();

Qui, stiamo memorizzando l'oggetto restituito dal createStudent()metodo in student1.

Articoli interessanti...