【问题标题】:c++ beginner segmentation fault when using strings使用字符串时的c ++初学者分段错误
【发布时间】:2014-03-10 16:32:16
【问题描述】:

我正在尝试使用 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 而你没有,所以这是个问题。
  • 令我印象深刻的是,您甚至遇到了段错误。如果不返回错误,编译器至少应该警告您。
  • 在和 tada 中添加了退货声明!非常感谢 faranwath
  • @faranwath 添加你的答案,你会得到支持而不是你的评论。
  • @EricFortin:可悲的是,一些流行的编译器不会发出警告(更不用说拒绝带有警告的代码),除非你告诉他们。

标签: c++ string class segmentation-fault


【解决方案1】:

你说myclass::replace 每次被调用时都会返回一个std::string,但你实际上并没有returned 任何东西!然后发生的事情进入了未定义行为的领域,这通常意味着你的程序会行为不端,最终甚至会kill your cat

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

【讨论】:

    【解决方案2】:

    这里

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-09
      相关资源
      最近更新 更多