Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while overloading operator (must be a nonstatic member function)

Tags:

People also ask

Which operator must be a member function?

The overloaded operator must be added as a member function of the left operand.

What is a nonstatic member function?

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)

Which operator Cannot be overloaded only as member function?

Dot (.) operator can't be overloaded, so it will generate an error.

What is the correct syntax to overload the operator?

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.