Jump to content

[C++] Functii C++


growndex.
 Share

Recommended Posts

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.

4564.thumb.png.fb21994d413003dda72b0e51a2b70277.pngTreceti 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

8776.thumb.png.2d75d308f724915cac48ee3361e7c0e7.pngReturnare 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 by growndex.
Link to comment
Share on other sites

  • Tupi locked this topic
Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.