重载操作符时出错(必须是非静态成员函数) [英] Error while overloading operator (must be a nonstatic member function)

查看:552
本文介绍了重载操作符时出错(必须是非静态成员函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

但不幸的是我收到错误'S&

But unfortunately I get error 'S& operator=(const S&)' must be a nonstatic member function.

推荐答案

您缺少类名:

这是全局运算符, = 不能是全局运算符:

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

这篇关于重载操作符时出错(必须是非静态成员函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆