[英]c++ beginner segmentation fault when using strings
I'm trying to set up a basic class using std::string as a function type and a variable type, but using both gives me a segmentation fault. 我正在尝试使用std :: string作为函数类型和变量类型来设置基本类,但是同时使用这会给我带来分段错误。 If I delete either the function or the variable, everything is fine. 如果我删除函数或变量,一切都很好。 I'm sure I'm making a really stupid mistake! 我确定我犯了一个非常愚蠢的错误! This is my code: main.cpp 这是我的代码:main.cpp
#include <iostream>
#include <cstdlib>
#include <string>
#include "myclass.h"
int main()
{
myclass obj;
obj.replace();
return EXIT_SUCCESS;
};
myclass.h myclass.h
#ifndef MYCLASS_H_
#define MYCLASS_H_
#include <string>
class myclass
{
private:
std::string instruction;
public:
myclass();
std::string replace();
};
#endif
myclass.cpp 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;
}
You said myclass::replace
was to return an std::string
every time it gets called, but you didn't actually return
ed anything! 您说myclass::replace
是每次调用std::string
都会返回它,但实际上并没有return
ed! What happened then enters the realm of undefined behavior, which usually means your program will misbehave and eventually could even kill your cat . 然后,发生的事情进入了不确定行为的境界,这通常意味着您的程序行为不当,甚至可能杀死您的猫 。
The solution is to add a return
statement at the end of the function. 解决方案是在函数末尾添加return
语句。
Here 这里
obj.replace();
you have discarded return value, std::string
You can discard the return value. 您已放弃返回值std::string
可以放弃该返回值。 It's no good style in general, but you can always do it. 一般而言,这不是一个好的样式,但是您可以随时做到。 But the actual problem is that you don't return anything from replace
function: 但是实际的问题是您没有从replace
函数返回任何内容:
std::string myclass::replace()
{
std::cout<<"I replace"<<std::endl;
//... return statement is missing
}
solution: 解:
std::string myclass::replace()
{
std::cout<<"I replace"<<std::endl;
return std::string();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.