程序结束,退出码为10
Program finished with exit code 10
我是一个c++初学者。我试图实现复制构造函数。我希望我遵循了复制构造函数的正确语法。但是每当我编译我的代码时,它会没有任何错误地完成,但在运行时它会说"程序结束,退出码为10"。我在clionide中工作。当我在Mac终端上尝试时,它显示"Bus error: 10"
我可以找出是复制构造函数导致了这个问题。我试着注释它并运行程序,它工作得很好,当我取消注释时,导致了上面的问题。
请帮我找出我错在哪里。
谢谢。下面是我的代码:
#include <iostream>
using namespace std;
class Person {
char *name;
int age;
public:
Person ();
Person (char *, int age = 18);
Person (const Person &p);
void output ();
};
Person ::Person() {
name = new char[20]();
age = 0;
}
Person ::Person(char *str, int age) {
name = new char[50]();
strcpy(name, str);
this->age = age;
}
Person ::Person(const Person &p) {
strcpy(name, p.name);
age = p.age;
}
void Person ::output() {
cout << "nName = " << name;
cout << "nAge = " << age << endl;
cout <<"-------------------------------------------------------------------------------------------------------------------------n";
}
int main () {
Person p1;
Person p2("Name");
Person p3 ("Name", 20);
Person p4 = p2;
cout << "nThe Output of the Object Called by Default Constructornn";
p1.output();
cout << "nThe Output of the Object Called by Parameterised Constructor with Default Argumentnn";
p2.output();
cout << "nThe Output of the Object Called by Parameterised Constructor Overriding Default Argument nn";
p3.output();
cout << "nThe Output of the Object Called by Copy Constructor (Copying p2 Object that is the second output)nn";
p4.output();
return 0;
}
如果我只从你的问题的标题回答你的问题,答案将非常简单。
但是首先请阅读如何创建一个最小的,可重复的例如,因为它可以帮助其他人理解和检查你的代码。
exit()
是终止内置函数,用于正常终止程序。
,它接受一个参数Status code
。也表示两种简单状态
- 0或
EXIT_SUCCESS
(宏)表示成功、exit(0)
或exit(EXIT_SUCCESS)
。 - 如果是
EXIT_FAILURE
,表示失败、exit(1)
或exit(EXIT_FAILURE)
。
所以对于exit(10)
或exit(1)
的任何其他值,它表示错误。
要了解有关exit()的更多信息,请参阅此处:
- exit() - cpluscplus
- exit() vs _Exit()在C和c++ - GeaksforGeaks
- exit(), abort()和assert() - GeaksforGeaks
现在从你的代码中显示,你是新的
pointers
,所以它会很好地为你读这篇文章,因为它会给吗指导如何以正确的方式使用指针以防止out of memory
、memory leaks
和Segfault
错误。c++核心指南:资源管理规则
分配
Person ::Person(const Person &p) {
strcpy(name, p.name);
age = p.age;
}
在向成员name
复制数据之前,应该为其分配strlen(p.name)+1
字节大小的内存
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在这个代码结束循环中没有得到结束
- 创建LinkedList退出,返回代码为-11(SIGSEGV)
- 当我在main中声明了我的2d数组时,为什么我的程序会退出
- 试图对缓存进行跨步测试,但程序并没有结束
- 如何让LLDB在成功时退出,在失败时等待
- C++控制台应用程序阻止退出
- 程序在执行程序的其余部分之前退出
- 构造函数在退出函数时无法初始化一个参数
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么异常不退出程序?
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- 程序显示以退出代码 0; 结束
- 为什么它停止并以退出代码 11 结束?
- 程序过早结束,可能已经崩溃了.退出代码0xc0000005
- 退出(0)未结束程序
- 如何停止任务运行终端在程序以视觉工作室代码结束后自动退出
- 程序在结束时退出
- 如何在给定的openmp线程结束时退出程序
- 程序结束,退出码为10