【发布时间】: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++ 编译器,并且肯定添加了所需的库。
-
复制并粘贴您的实际代码。所有的。足以重现问题。