为什么会出现“非法指令”错误?

时间:2020-08-04 15:41:20

标签: c++

这是课程

using namespace std;

class Animal
{
    public:

    Animal()
    {
        using std::cout;

        cout << "[+]Animal created...";
    }
  
    string makeSound(std::string name,std::string sound){
        
        using std::cout;
        
        cout<<name <<"goes"<<sound;
            
    }
        
    string eatsFood(std::string name,std::string food){
        
        using std::cout;

        cout<<name<<" eats " <<food;
    }
};

这是源文件

#include<iostream>
#include<conio.h>
#include<string>

#include "animal.h"

using namespace std;


int main()
{   
    Animal obj;
 
    obj.makeSound( "dog","woof! woof!");
 
    obj.eatsFood("dog"," Meat and vagitables");
 
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您的makeSoundeatFood函数被声明为返回string,但是实际上您并不是从这些函数返回。这会引起未定义的行为,并可能导致illegal instruction错误。

如果使它们成为void返回函数,就可以了。 demo

此外,尤其在头文件中,请勿使用using namespace std;