Roc*_*etq 13 c++ operator-overloading
我正在自己编写字符串类.我有这样的代码.我只想超载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&)'必须是非静态成员函数.
Pio*_*ycz 21
你缺少班级名称:
这是全球运营商,=不能全球化:
S &operator=(const S &s)
Run Code Online (Sandbox Code Playgroud)
您必须将其定义为类函数:
S & S::operator=(const S &s)
// ^^^
Run Code Online (Sandbox Code Playgroud)
我相信 PiotrNycz 已经提供了合理的答案。在这里请原谅我再补充一个词。
在 C++ 中,赋值运算符重载函数不能是friend function. 对 operator= 使用友元函数,将导致相同的编译器错误“重载 = 运算符必须是非静态成员函数”。
| 归档时间: |
|
| 查看次数: |
30451 次 |
| 最近记录: |