Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 "객체를 반환"하는 방법은 무엇입니까?


객체는 클래스의 인스턴스입니다. 메모리는 객체가 생성될 때만 할당되고 클래스가 정의될 ​​때는 할당되지 않습니다.

return 키워드를 사용하여 함수에서 객체를 반환할 수 있습니다. 이것을 증명하는 프로그램은 다음과 같습니다 -

예시

#include <iostream>
using namespace std;
class Point {
   private:
   int x;
   int y;
   public:
   Point(int x1 = 0, int y1 = 0) {
      x = x1;
      y = y1;
   }
   Point addPoint(Point p) {
      Point temp;
      temp.x = x + p.x;
      temp.y = y + p.y;
      return temp;
   }
   void display() {
      cout<<"x = "<< x <<"\n";
      cout<<"y = "<< y <<"\n";
   }
};
int main() {
   Point p1(5,3);
   Point p2(12,6);
   Point p3;
   cout<<"Point 1\n";
   p1.display();
   cout<<"Point 2\n";
   p2.display();
   p3 = p1.addPoint(p2);
   cout<<"The sum of the two points is:\n";
   p3.display();
   return 0;
}

출력

위 프로그램의 출력은 다음과 같습니다.

Point 1
x = 5
y = 3
Point 2
x = 12
y = 6
The sum of the two points is:
x = 17
y = 9

이제 위의 프로그램을 이해해보자.

Point 클래스에는 x와 y라는 두 개의 데이터 멤버가 있습니다. 매개변수화된 생성자와 2개의 멤버 함수가 있습니다. addPoint() 함수는 두 개의 Point 값을 더하고 합계를 저장하는 객체 temp를 반환합니다. display() 함수는 x와 y의 값을 출력합니다. 이에 대한 코드 스니펫은 다음과 같습니다.

class Point {
   private:
   int x;
   int y;
   public:
   Point(int x1 = 0, int y1 = 0) {
      x = x1;
      y = y1;
   }
   Point addPoint(Point p) {
      Point temp;
      temp.x = x + p.x;
      temp.y = y + p.y;
      return temp;
   }
   void display() {
      cout<<"x = "<< x <<"\n";
      cout<<"y = "<< y <<"\n";
   }
};

main() 함수에서 Point 클래스의 3개 객체가 생성됩니다. p1 및 p2의 첫 번째 값이 표시됩니다. 그런 다음 addPoint() 함수를 호출하여 p1과 p2에 있는 값의 합을 찾아 p3에 저장합니다. p3의 값이 표시됩니다. 이에 대한 코드 스니펫은 다음과 같습니다.

Point p1(5,3);
Point p2(12,6);
Point p3;
cout<<"Point 1\n";
p1.display();
cout<<"Point 2\n";
p2.display();
p3 = p1.addPoint(p2);
cout<<"The sum of the two points is:\n";
p3.display();