이 튜토리얼은 C++에서 함수의 매개변수로 객체를 전달하고, 함수에서 객체를 반환하는 방법을 실용적인 예제와 모범 사례와 함께 설명합니다.
예제 1: 함수에 객체 전달하기
// 두 학생의 평균 점수 계산 C++ 프로그램 #include <iostream> using namespace std; class Student { public: double marks; // marks 초기화 생성자 Student(double m) : marks(m) {} }; // Student 객체를 매개변수로 받는 함수 void calculateAverage(Student s1, Student s2) { double average = (s1.marks + s2.marks) / 2.0; cout << "Average Marks = " << average << endl; } int main() { Student student1(88.0), student2(56.0); calculateAverage(student1, student2); return 0; }
출력
Average Marks = 72
여기서 두 Student 객체 student1과 student2를 calculateAverage()에 값으로 전달했습니다. 값 전달은 복사본을 생성하므로 객체가 크면 참조 전달을 고려하세요.