C++ Segmentation fault:11,试图重载operator <<

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++)

Dav*_*rtz 8

你有一个堆栈溢出.您的operator<<呼叫operator<<(具有相同数据的相同功能).

  • +1:实际上你的链接应该指向你的答案.这将是递归的完美示例:D. (3认同)

Zet*_*eta 6

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)

  • 确保你理解*为什么*这有效,你的代码与Zeta所显示的修正版本之间的区别是什么. (2认同)