Como passar e retornar objeto de funções C ++?

Neste tutorial, aprenderemos a passar objetos para uma função e retornar um objeto de uma função na programação C ++.

Na programação C ++, podemos passar objetos para uma função de maneira semelhante à passagem de argumentos regulares.

Exemplo 1: C ++ Passar Objetos para Função

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

Resultado

 Marcas Médias = 72

Aqui, passamos dois Studentobjetos student1 e student2 como argumentos para a calculateAverage()função.

Passe objetos para funcionar em C ++

Exemplo 2: C ++ Return Object from a Function

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

Resultado

 Marcas 1 = 96,5 Marcas 2 = 75
Retorna o objeto da função em C ++

Neste programa, criamos uma função createStudent()que retorna um objeto de Studentclasse.

Chamamos createStudent()do main()método.

 // Call function student1 = createStudent();

Aqui, estamos armazenando o objeto retornado pelo createStudent()método no student1.

Artigos interessantes...