原代碼存在多個關鍵錯誤:char* name 淺拷貝導致雙重釋放、構造函數參數應為 const char*、cout << a.PrintName() 嘗試輸出 void 返回值。
#include <iostream>
#include <cstring>
using namespace std;
class Person {
private:
char* name;
public:
Person(const char* n) { // const char* 參數
name = new char[strlen(n) + 1];
strcpy(name, n); // 深拷貝
}
~Person() { delete[] name; } // 析構釋放
// 拷貝構造/賦值運算符 (三/五法則) 略,實際必須實現
void PrintName() const { // const 成員函數
cout << "The name is: " << name;
}
};
class Student : public Person {
private:
long number;
public:
Student(const char* n, long num) : Person(n), number(num) {}
void PrintInfo() const {
PrintName(); // 調用基類方法
cout << ", The number is: " << number;
}
};
int main() {
Person a("張三");
a.PrintName(); // 直接調用,無返回值
cout << endl;
Student b("李四", 142180217);
b.PrintInfo();
cout << endl;
return 0;
}
name = new char[...]; strcpy(...),析構 delete[]。const char*,方法 const。PrintName() 內部輸出,main 中直接調用,不嘗試 cout << void。Person a("張三") 直接傳字面量,無需臨時 char[] (C++ 自動轉換)。管理動態內存的類必須實現:
或使用 std::string 替代 char* 由編譯器自動生成 (Rule of Zero)。
修正內存管理與輸出邏輯,程序正常運行輸出姓名與學號。