Hello. I would like to ask you to explain or give some example of overloading operators to me. I mean something like ==. Thank you.
This is a discussion on Overloading(creating) operators (BCPPB 5.0) within the C++ Programming forums, part of the General Programming Boards category; Hello. I would like to ask you to explain or give some example of overloading operators to me. I mean ...
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; }
I used to be an adventurer like you... then I took an arrow to the knee.
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.