【问题标题】:Error while overloading operator (must be a nonstatic member function)重载运算符时出错(必须是非静态成员函数)
【发布时间】:2012-10-02 15:01:20
【问题描述】:

我正在自己编写字符串类。我有这样的代码。我只想重载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;
}

但不幸的是我得到错误'S& operator=(const S&)' must be a nonstatic member function。

【问题讨论】:

  • 这段代码 sn-p 用 g++ 为我编译。
  • 不确定你在做什么,但函数编译良好,memcpy 声明:liveworkspace.org/code/92ac98695817213f6c15af241904d165
  • 您不会在类定义后缺少分号吧?
  • 我使用 G++ 编译器,并且肯定添加了所需的库。
  • 复制并粘贴您的实际代码。所有的。足以重现问题。

标签: c++ operator-overloading


【解决方案1】:

我相信 PiotrNycz 提供了合理的答案。在这里,请原谅我再补充一个字。

在 c++ 中,赋值运算符重载函数不能是 friend function。对 operator= 使用友元函数,会导致同样的编译器错误“重载 = 运算符必须是非静态成员函数”。

【讨论】:

  • 这应该是对另一个答案的评论,如果它只是一个澄清的话。或者,删除关于它是“多一个词”的注释并使其成为正确答案。
【解决方案2】:

您缺少班级名称:

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

S &operator=(const S &s)

您必须将其定义为类函数:

S & S::operator=(const S &s)
//  ^^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 2016-05-29
    • 2011-06-05
    • 2012-06-25
    相关资源
    最近更新 更多