Add*_*son 2 c++ runtime-error segmentation-fault
我正在尝试重载此类中的<<运算符,但这是输出:
Hello,
Segmentation fault: 11
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
test.cc:
#include <iostream>
#include "class.h"
#include <string>
using namespace std;
int main() {
MYString s("Hello");
MYString s2;
string hello = "Hello";
cout << s.text << ", " << s2.text << endl;
cout << "S: " << s << endl;
hello[0] = 'M';
cout << hello << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是class.h:
#ifndef CLASS_H
#define CLASS_H
#include <string>
using namespace std;
class MYString {
public:
string text;
MYString(string data="") {
text = data;
}
friend ostream& operator << (ostream& os, const MYString& data) {
os << data;
return(os);
}
};
#endif
Run Code Online (Sandbox Code Playgroud)
编译很好,但我不知道它为什么说"分段错误:11".我也不知道这意味着什么.有人能告诉我如何解决这个问题吗?而且我也是C++的新手
(而且我也知道这段代码真的没用,但我只是想学习东西并习惯C++)
friend ostream& operator << (ostream& os, const MYString& data) {
os << data; // calls 'ostream& operator<<(ostream&,const MYstring&)' -- oops
return(os);
}
Run Code Online (Sandbox Code Playgroud)
无限递归.os << data.text改为使用:
friend ostream& operator << (ostream& os, const MYString& data) {
os << data.text;
return(os);
}
Run Code Online (Sandbox Code Playgroud)