class Employee {
char name[32];
char street[64];
char city[32];
char zip[16];
public:
Employee(const char* n, const char* s, const char* c, const char* z) {
strcpy(name, n);
strcpy(street, s);
strcpy(city, c);
strcpy(zip, z);
}
void changeName(const char* n) { strcpy(name, n); }
void display() const {
cout << name << '\n' << street << '\n' << city << '\n' << zip << '\n';
}
};
char* strcpy(char* dest, const char* src);strncpy(dest, src, sizeof(dest)-1); dest[sizeof(dest)-1]='\0'; 或改用 std::string。<cstring> (C++) 或 <string.h> (C)。class Employee {
std::string name, street, city, zip;
public:
Employee(std::string n, std::string s, std::string c, std::string z)
: name(std::move(n)), street(std::move(s)), city(std::move(c)), zip(std::move(z)) {}
void changeName(std::string n) { name = std::move(n); }
void display() const { cout << name << '\n' << street << '\n' << city << '\n' << zip << '\n'; }
};
避免手動記憶體管理、緩衝區溢位、規則三/五/零麻煩。