สมมติว่าเราได้รับความยาวและความกว้างของสี่เหลี่ยม 2 รูป ต้องคำนวณพื้นที่โดยใช้คลาส สร้างคลาส Rectangle มีแอตทริบิวต์ l, b และฟังก์ชัน area() คืนค่าพื้นที่
เช่น (10,9), (8,6) ผลลัพธ์: 90 และ 48
ขั้นตอนการแก้ปัญหา
- สร้างคลาส Rectangle มี l, b เป็น private
- ฟังก์ชัน input(len, bre) ตั้งค่า l, b
- ฟังก์ชัน area() คืนค่า l * b
ตัวอย่างโค้ด
#include <iostream> using namespace std; class Rectangle{ private: int l, b; public: void input(int len, int bre){ l = len; b = bre; } int area(){ return l * b; } }; int main(){ Rectangle r1, r2; r1.input(10, 9); r2.input(8, 6); cout << "Area of r1: " << r1.area() << endl; cout << "Area of r2: " << r2.area() << endl; }
อินพุต
(10, 9), (8, 6)
เอาต์พุต
Area of r1: 90 Area of r2: 48