C++ 重载运算符时出错(必须是非静态成员函数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12848171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error while overloading operator (must be a nonstatic member function)
提问by Rocketq
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.
我正在自己编写字符串类。我有这样的代码。我只想超载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]='S &operator=(const S &s)
';
}
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.
但不幸的是我得到错误'S& operator=(const S&)' must be a nonstatic member function。
回答by PiotrNycz
You are missing class name:
您缺少班级名称:
This is global operator, =
cannot be global:
这是全局运算符,=
不能是全局的:
S & S::operator=(const S &s)
// ^^^
You must define this as class function:
您必须将其定义为类函数:
##代码##回答by Spectral
I believe PiotrNycz has provided the reasonable answer. Here please pardon me to add one more word.
我相信 PiotrNycz 已经提供了合理的答案。在这里请原谅我再补充一个词。
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".
在 C++ 中,赋值运算符重载函数不能是friend function
. 对 operator= 使用友元函数,将导致相同的编译器错误“重载 = 运算符必须是非静态成员函数”。