Jump to content
Sign in to follow this  
Vlam

[C++] Functii C++

Recommended Posts

Posted (edited)

Crowland

 

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 calcula Average() 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.

Edited by Vlam

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  


×
×
  • Create New...