[英]Dev C++ keeps crashing when I run this code. I cannot figure out why
I do not know whats going on. 我不知道怎么回事。 The program seemed to work fine on visual studio.
该程序在Visual Studio上似乎运行良好。 Maybe I got something wrong and I cant spot it.. Please someone help me out with this one.
也许我出了点问题,我找不到它。请有人帮我解决这个问题。
#include <iostream>
#include<string>
#include<cstdlib>
using namespace std;
class Aokiji
{
private:
string name1;
string name2;
public:
string setName(string x)
{
name1=x;
}
string getName()
{
return name1;
}
};
int main()
{
Aokiji Grapes;
Grapes.setName("I got it!");
cout<< Grapes.getName()<< endl;
system("pause");
}
Your setName() function doesn't return anything, but it's supposed to return a std::string. 您的setName()函数不会返回任何内容,但是应该返回一个std :: string。 You need to return a value, or make the setName() function void (which is probably what it should be)
您需要返回一个值,或使setName()函数无效(这可能应该是这样)
As was pointed at by PaulMacKenzie, the problem is the missing return statement. 正如PaulMacKenzie所指出的那样,问题在于缺少return语句。 This is the reason why using C++, one should always use the
-Werror=return-type
flag to ensure that functions do not miss return statements. 这就是为什么使用C ++时应始终使用
-Werror=return-type
标志以确保函数不会丢失return语句的原因。
I'm amazed C++ allows that, actually. 我很惊讶,C ++实际上允许这样做。 The only case I think where it is legitimate that a function could miss a return statement is if it is supposed to return something, but instead it throws an exception and therefore does not return.
我认为函数可以错过return语句的唯一合理情况是,如果该函数应返回某些内容,但会引发异常,因此不会返回。 But that's a very narrow use case, and adding a dummy return statement in that case does not cost anything.
但这是一个非常狭窄的用例,在这种情况下添加一个虚拟return语句不会花费任何费用。
Replace setName() method in your code by: 将代码中的setName()方法替换为:
void setName(string x) { name1 = x; }
And you need return 0; 您需要返回0; in int main() .
在int main()中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.