[英]Program finished with exit code 10
我是 C++ 的初學者。 我正在嘗試實現復制構造函數。 我希望我遵循了復制構造函數的正確語法。 但是每當我編譯我的代碼時,它都會完成而不會出現任何錯誤,但在運行時它會顯示“程序已完成,退出代碼為 10”。 我在 Clion IDE 中工作。 當我在 Mac 終端中嘗試時,它顯示“總線錯誤: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 Constructor\n\n";
p1.output();
cout << "\nThe Output of the Object Called by Parameterised Constructor with Default Argument\n\n";
p2.output();
cout << "\nThe Output of the Object Called by Parameterised Constructor Overriding Default Argument \n\n";
p3.output();
cout << "\nThe Output of the Object Called by Copy Constructor (Copying p2 Object that is the second output)\n\n";
p4.output();
return 0;
}
如果我僅從您的問題標題來回答您的問題,那么答案將非常簡單。
但首先請閱讀如何創建最小的、可重現的示例,因為它有助於其他人理解和檢查您的代碼。
exit()
是一個終止內置函數,用於正常終止程序。
它需要一個名為Status code
參數。 這也表示 2 個簡單的狀態。
EXIT_SUCCESS
(宏),則表示成功, exit(0)
或exit(EXIT_SUCCESS)
。EXIT_FAILURE
,則表示失敗、 exit(1)
或exit(EXIT_FAILURE)
。 因此,對於exit(10)
或exit(1)
任何其他值,它表示錯誤。
要了解有關 exit() 的更多信息,請參見此處:
現在,從您的代碼中可以看出您對
pointers
不熟悉,因此閱讀本文對您來說非常有用,因為它將為您提供有關如何以正確方式使用指針以防止out of memory
和memory leaks
指南規則和Segfault
錯誤。
你是被配置了嗎?
Person ::Person(const Person &p) { strcpy(name, p.name); age = p.age; }
在將數據復制到成員name
,您應該為成員name
分配strlen(p.name)+1
字節大小的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.