growndex. Posted January 27, 2021 Share Posted January 27, 2021 (edited) In acest tutorial, vom invata sa transmitem obiecte unei functii si sa returnam un obiect dintr-o functie in programarea C++. In programarea C++, putem transmite obiecte unei functii intr-un mod similar cu cel al transmiterii argumentelor obisnuite. Exemplul 1: C++ Pass Objects to Function: #include <iostream> 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; } Output: Average Marks = 72 Aici, am trecut doua student obiecte student1 si student2 ca argumente pentru a calculaAverage() functie. Treceti obiectele pentru a functiona în C++. Exemplul 2: C++ Return Object dintr-o functie: 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; } Output: Marks1 = 96.5 Marks2 = 75 Returnare obiect din functie in C++. In acest program, am creat o functie createStudent() care returneaza un obiect al clasei Student. Am numit createStudent() din metoda main(). // Call function student1 = createStudent(); Aici, stocam obiectul returnat prin metoda createStudent() in student1. Pot face tutoriale si despre Flow Control,Functions,Arrays & String,Structures,etc..dar nu vad rostul daca nu vad interes la topicurile de tutoriale. Edited January 27, 2021 by growndex. 1 Link to comment Share on other sites More sharing options...
Tupi Posted January 31, 2021 Share Posted January 31, 2021 Mulțumim pentru tutorial! Link to comment Share on other sites More sharing options...
Recommended Posts