อ็อบเจ็กต์คือตัวอย่างของคลาส หน่วยความจำจะได้รับการจัดสรรเมื่อวัตถุถูกสร้างขึ้นเท่านั้น ไม่ใช่เมื่อมีการกำหนดคลาส
ฟังก์ชันสามารถส่งคืนอ็อบเจ็กต์โดยใช้คีย์เวิร์ด 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
ตอนนี้ เรามาทำความเข้าใจโปรแกรมข้างต้นกัน
class Point มีสมาชิกข้อมูลสองตัวคือ x และ y มีตัวสร้างพารามิเตอร์และฟังก์ชันสมาชิก 2 ตัว ฟังก์ชัน addPoint() เพิ่มค่าจุดสองค่าและส่งกลับค่าอุณหภูมิของวัตถุที่เก็บผลรวม ฟังก์ชั่น 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 จะปรากฏขึ้น จากนั้นจะพบผลรวมของค่าใน 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();