Hello. I would like to ask you to explain or give some example of overloading operators to me. I mean something like ==. Thank you.
Hello. I would like to ask you to explain or give some example of overloading operators to me. I mean something like ==. Thank you.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Code:struct foo { int age; string fname; string lname; }; bool operator==(const foo& lhs,const foo& rhs) { return lhs.age == rhs.age && lhs.fname == rhs.fname && lhs.lname == rhs.lname; }
"Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
-Christopher Hitchens
Code:#include <iostream> #include <string> using namespace std; class Apple { private: string color; public: Apple(string c) { color = c; } Apple& operator=(const Apple& rhs) //the return value is so you can write: //apple1 = apple2 = apple3; { if(this == &rhs) //if they are the same objects, //no need to do any assignments return *this; else if(rhs.color == "black") //don't do the assignment { cout<<"The Apple is rotten."<<endl; return *this; } else //do the assignment { this->color = rhs.color; return *this; } } void show() { cout<<"My apple's color is: "<<color<<endl; } }; int main() { Apple redApple("red"); Apple blackApple("black"); Apple greenApple("green"); redApple = greenApple; redApple.show(); cout<<endl; greenApple = blackApple; greenApple.show(); cout<<endl; blackApple = greenApple = redApple; blackApple.show(); greenApple.show(); redApple.show(); return 0; }
Last edited by 7stud; 08-15-2005 at 01:30 PM.
Thak all of you.