27

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.

9
  • 2
    This code snippet compiles for me with g++.
    – Neil
    Oct 11, 2012 at 20:43
  • 1
    Not sure what you're doing, but the function compiles fine with memcpy declared: liveworkspace.org/code/92ac98695817213f6c15af241904d165
    – chris
    Oct 11, 2012 at 20:43
  • You are not missing a semicolon after the class definition, are you? Oct 11, 2012 at 20:44
  • 2
    I use G++ compiler, and for sure I added required libraries.
    – Rocketq
    Oct 11, 2012 at 20:48
  • 2
    Copy and paste your actual code. All of it. Enough to reproduce the problem. Oct 11, 2012 at 20:51

2 Answers 2

45

You are missing class name:

This is global operator, = cannot be global:

S &operator=(const S &s)

You must define this as class function:

S & S::operator=(const S &s)
//  ^^^
1
  • for god's sake!
    – gonidelis
    Apr 19, 2022 at 5:16
7

I believe PiotrNycz has provided the reasonable answer. Here please pardon me to add one more word.

In c++, assignment operator overloading function couldn't be friend function. Using friend function for operator=, will cause the same compiler error "overloading = operator must be a nonstatic member function".

1
  • 4
    This should really be a comment on the other answer, if it's just a clarification. Alternatively, remove the note about it being "one more word" and make it a proper answer.
    – anon
    May 9, 2016 at 17:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.