相关疑难解决方法(0)

重载运算符时出错(必须是非静态成员函数)

我正在自己编写字符串类.我有这样的代码.我只想超载operator=.这是我的实际代码,我在代码的最后部分得到错误.

#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;
}
Run Code Online (Sandbox Code Playgroud)

但不幸的是我收到错误'S&operator =(const S&)'必须是非静态成员函数.

c++ operator-overloading

13
推荐指数
2
解决办法
3万
查看次数

标签 统计

c++ ×1

operator-overloading ×1