繁体   English   中英

使用字符串时的c ++初学者分段错误

[英]c++ beginner segmentation fault when using strings

我正在尝试使用std :: string作为函数类型和变量类型来设置基本类,但是同时使用这会给我带来分段错误。 如果我删除函数或变量,一切都很好。 我确定我犯了一个非常愚蠢的错误! 这是我的代码:main.cpp

#include <iostream>
#include <cstdlib>
#include <string>
#include "myclass.h"

int main()
{

    myclass obj;
    obj.replace();

    return EXIT_SUCCESS;
};

myclass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_
#include <string>

class myclass
{
    private:
        std::string instruction;

    public:
        myclass();
        std::string replace();
}; 

#endif

myclass.cpp

#include "myclass.h"
#include <iostream>


myclass::myclass()
{
    std::cout<<"I am the constructor"<<std::endl;
}

std::string myclass::replace()
{
    std::cout<<"I replace"<<std::endl;
}

您说myclass::replace是每次调用std::string都会返回它,但实际上并没有return ed! 然后,发生的事情进入了不确定行为的境界,这通常意味着您的程序行为不当,甚至可能杀死您的猫

解决方案是在函数末尾添加return语句。

这里

obj.replace();

您已放弃返回值std::string可以放弃该返回值。 一般而言,这不是一个好的样式,但是您可以随时做到。 但是实际的问题是您没有从replace函数返回任何内容:

std::string myclass::replace()
{
    std::cout<<"I replace"<<std::endl;
    //... return statement is missing
}

解:

std::string myclass::replace()
{
    std::cout<<"I replace"<<std::endl;
    return std::string();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM