Skip to content

Instantly share code, notes, and snippets.

@krysseltillada
Created July 6, 2015 13:01
Show Gist options
  • Save krysseltillada/a0d4ad27402f69a56289 to your computer and use it in GitHub Desktop.
Save krysseltillada/a0d4ad27402f69a56289 to your computer and use it in GitHub Desktop.
PERSON_H with operator overloading =
#include <iostream> /// iostream header ---> std::cout; std::endl; std::cin; std::ostream
#include "Person.h" /// include the PERSON_H header ----> operator=, std::ostream , std::istream
int main()
{
Person p1, p2; /// declared two objects named p1 and p2
p1.name = "kryssel"; /// assigns kryssel in data member name of p1
p1.address = "rivera compound saint joseph sub pulang lupa dos las pinas city"; /// assigns the address in data member of p1
std::ostream &print = std::cout; /// declared a ostream type that is a reference named print and bounds two std::cout;
print << p1.name << std::endl /// print == std:cout;
<< p1.address << std::endl;
print << std::endl
<< "object p2 stores the data members in object p1 ";
p2 = p1; /// assigns p1 into p2 --> see Person.h operator=
print << p2.name << std::endl /// prints p2 data members
<< p2.address << std::endl;
return 0;
}
#ifndef PERSON_H /// header declaration --> if not define
#define PERSON_H /// then define PERSON_H as a header
#include <iostream> /// std::end; std::cout;
#include <string> /// std::string;
struct Person {
Person operator=(const Person &person_p) { /// declares a function operator = to mimic a var = var assignment
name = person_p.name; /// the left operand is the "this object" which is p2 and the right operand which we get in the argument is p1
address = person_p.address; /// assigning those values
return *this; /// dereferencing "this object" which is p2 because "this" is implicitly initialize what function object used which is p2 and returns the object
}
std::string name , address; /// declared a two string named name and address
};
#endif // end of the header
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment