简体   繁体   中英

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. 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. You need to return a value, or make the setName() function void (which is probably what it should be)

As was pointed at by PaulMacKenzie, the problem is the missing return statement. 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.

I'm amazed C++ allows that, actually. 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. But that's a very narrow use case, and adding a dummy return statement in that case does not cost anything.

Replace setName() method in your code by:

 void setName(string x) { name1 = x; } 

And you need return 0; in int main() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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