สมมติว่าเรามีคลาส Person ที่มีแอตทริบิวต์ first_name และ last_name พร้อมเมธอด get_first_name() และ get_last_name() เราต้องโหลดโอเปอเรเตอร์แทรก (<<) เพื่อพิมพ์ชื่อ-นามสกุลผ่าน cout
เช่น Person p("Sumit", "Ray") ผลลัพธ์: "First name - Sumit, Last name - Ray"
ขั้นตอนการแก้ปัญหา
- โหลดโอเปอเรเตอร์ << นอกจากคลาส
- คืนค่า ostream reference
- รับพารามิเตอร์ ostream& os และ Person& p
- ใช้ os แยกส่วนข้อมูลของออบเจกต์
- คืนค่า os
ตัวอย่างโค้ด
#include <iostream> using namespace std; class Person { private: string f_name, l_name; public: Person(string first_name, string last_name) : f_name(first_name), l_name(last_name) {} string& get_first_name() { return f_name; } string& get_last_name() { return l_name; } }; ostream& operator<<(ostream& os, Person& p) { os << "First name: " << p.get_first_name() << ", Last name: " << p.get_last_name(); return os; } int main(){ Person p("Sumit", "Ray"); cout << p << ", he is our member."; }
อินพุต
p("Sumit", "Ray")
เอาต์พุต
First name: Sumit, Last name: Ray, he is our member.