산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C++ 함수에서 객체를 전달하고 반환하는 방법은 무엇입니까?

C++ 함수에서 개체를 전달하고 반환하는 방법은 무엇입니까?

이 자습서에서는 C++ 프로그래밍에서 함수에 개체를 전달하고 함수에서 개체를 반환하는 방법을 배웁니다.

C++ 프로그래밍에서는 일반 인수를 전달하는 것과 유사한 방식으로 객체를 함수에 전달할 수 있습니다.

예제 1:C++ 함수에 개체 전달

// C++ program to calculate the average marks of two students

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

출력

Average Marks = 72

여기에서 두 개의 Student을 전달했습니다. 개체 student1학생2 calculateAverage()에 대한 인수로 기능.

<그림> <시간>

예제 2:C++ 함수에서 객체 반환

#include <iostream>
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;
}

출력

Marks1 = 96.5
Marks2 = 75
<그림>

이 프로그램에서 createStudent() 함수를 만들었습니다. Student 객체를 반환합니다. 수업.

createStudent()를 호출했습니다. main()에서 방법.

// Call function
student1 = createStudent();

여기에 createStudent()에 의해 반환된 객체를 저장하고 있습니다. student1의 메소드 .


C 언어

  1. 3D 프린팅의 3단계와 작동 원리
  2. C# 클래스 및 개체
  3. C++ 클래스 및 개체
  4. C++ 메모리 관리:신규 및 삭제
  5. C++ 공개, 보호 및 비공개 상속
  6. C++ friend 함수 및 friend 클래스
  7. C 패스 주소 및 포인터
  8. 프로그램 예제가 있는 C++ 함수
  9. 사이버 범죄, 자연 재해 등으로부터 공급망을 보호하는 방법
  10. C++ 날짜 및 시간