首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 類中字元陣列私有成員:建構函數參數初始化與 strcpy 用法

     編輯:程式設計綜合問答

類別定義

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';
    }
};

strcpy 關鍵點

  • 原型: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)。

現代 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'; }
};

避免手動記憶體管理、緩衝區溢位、規則三/五/零麻煩。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved