如何在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的第一个值。然后通过调用function找到p1和p2中的值之和并将其存储在p3中addPoint()。显示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();