#include <iostream>
#include <string>
using namespace std;
class Person {
public:
Person(const string& first_name, const string& last_name) : first_name_(first_name), last_name_(last_name) {}
const string& get_first_name() const {
return first_name_;
}
const string& get_last_name() const {
return last_name_;
}
private:
string first_name_;
string last_name_;
};
// Overloading the << operator for Person class
ostream& operator<<(ostream& os, const Person& p) {
os << "first_name=" << p.get_first_name() << ",last_name=" << p.get_last_name();
return os;
}
int main() {
string first_name, last_name, event;
cin >> first_name >> last_name >> event;
auto p = Person(first_name, last_name);
cout << p << " " << event << endl;
return 0;
}
Code Explanation
The Person class is defined with private member variables first_name_ and last_name_, along with public member functions get_first_name() and get_last_name() to access the private variables.
The << operator is overloaded outside the class definition, taking the ostream& and const Person& as parameters. Inside the overloaded function, the get_first_name() and get_last_name() functions are used to retrieve the first and last names of the Person object and print them in the desired format.
In the main() function, the first name, last name, and event are input using cin.
An instance of the Person class is created with the provided first name and last name.
The cout statement prints the Person object p using the overloaded << operator, followed by the event string and a newline.
Input:
john doe registered
Output:
first_name=john,last_name=doe registered