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;
}
解决方案
您的makeSound
andeatFood
函数被声明为返回string
s,但您实际上并没有从这些函数中返回。这会调用未定义的行为,并可能导致illegal instruction
错误。
如果你让它们void
返回函数,你会没事的。演示。
此外,您不应该using namespace std;
特别在头文件中使用。
推荐阅读
- windbg - 弄清楚为什么 WinDBG 处于“忙”状态?
- operating-system - 将虚拟地址(逻辑地址)映射到物理地址
- python - 无法使用 _set | 查询外键相关对象 姜戈?
- javascript - 如何设置数据是否清除 onChange 函数不执行
- node.js - 使用 @kubernetes/client-node 修补 K8s 自定义资源
- java - 通过检查参数进行 URL 重定向
- gcc - gcc 无法链接 llc 输出的 objfile
- c# - 如何诊断 Microsoft 身份验证失败?
- sql - 将 NULL 替换为连接函数 SQL 中的自定义文本
- python - 第一个列表在附加另一个第二个列表后自动更新,然后在 Python 中更改第二个列表