The overloaded operator must be added as a member function of the left operand.
A non-static member function is a function that is declared in a member specification of a class without a static or friend specifier. ( see static member functions and friend declaration for the effect of those keywords)
Dot (.) operator can't be overloaded, so it will generate an error.
When we overload the binary operator for user-defined types by using the code: obj3 = obj1 + obj2; The operator function is called using the obj1 object and obj2 is passed as an argument to the function.
I'm writing string class on my own. And I have such code. I just want to overload operator=
. This is my actual code, and I get error in last part of code.
#include <iostream> #include <string.h> #include <stdlib.h> using namespace std; class S { public: S(); ~S() { delete []string;} S &operator =(const S &s); private: char *string; int l; }; S::S() { l = 0; string = new char[1]; string[0]='\0'; } S &operator=(const S &s) { if (this != &s) { delete []string; string = new char[s.l+1]; memcpy(string,s.string,s.l+1); return *this; } return *this; }
But unfortunately I get error 'S& operator=(const S&)' must be a nonstatic member function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With