如何在 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 值,並返回儲存和值的臨時物件。函式 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() 中,建立了類的 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();

更新於:26-6 月-2020

4K+次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.