首页 > 解决方案 > 为什么会出现“非法指令”错误?

问题描述

这是课

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

标签: c++

解决方案


您的makeSoundandeatFood函数被声明为返回strings,但您实际上并没有从这些函数中返回。这会调用未定义的行为,并可能导致illegal instruction错误。

如果你让它们void返回函数,你会没事的。演示

此外,您不应该using namespace std;特别在头文件中使用。


推荐阅读