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

瘦欲@ 提交于 2019-12-18 14:52:35

问题


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.


回答1:


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)
//  ^^^



回答2:


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".



来源:https://stackoverflow.com/questions/12848171/error-while-overloading-operator-must-be-a-nonstatic-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!