C 語言 struct 僅是數據聚合,無行為封裝。C++ class 引入訪問控制、成員函數、構造/析構函數、this 指針,實現真正的面向對象封裝。本文通過 Time 類演進,層層遞進講解核心機制。
| 關鍵字 | 默認訪問 | 適用場景 |
|---|---|---|
struct | public | 純數據載體(POD)、C 兼容 |
class | private | 封裝行為與數據、不變量維護 |
// C 風格:數據暴露,外部隨意修改
struct Time { int hour, minute, second; };
// C++ 風格:私有數據,公有接口
class Time {
private:
int hour, minute, second;
public:
void setTime(int h, int m, int s);
void tick();
void show();
};
Time()、Time(int h)、Time(int h,int m,int s)。Time(int h,int m,int s) : hour(h), minute(m), second(s) {} —— 必須用於 const/引用成員,效率更高。~Time() {},對象銷毀前自動調用(棧對象離開作用域、delete 堆對象)。Time* const this。this->hour = hour;。*this:Time& setHour(int h) { hour=h; return *this; }。| 級別 | 本類 | 派生類 | 外部 |
|---|---|---|---|
private | ✓ | ✗ | ✗ |
protected | ✓ | ✓ | ✗ |
public | ✓ | ✓ | ✓ |
原則:數據成員 private;接口 public;供派生類擴展的內部實現 protected。
class Base { public: Base() { cout<<"Base()"; } ~Base() { cout<<"~Base()"; } };
class Derived : public Base {
Member m;
public:
Derived() { cout<<"Derived()"; }
~Derived() { cout<<"~Derived()"; }
};
// 創建 Derived d;
// 輸出: Base() -> Member() -> Derived()
// 銷毀: ~Derived() -> ~Member() -> ~Base()
main 前,析構在 main 後。class Time {
int hour, minute, second;
public:
Time() : hour(0), minute(0), second(0) {}
Time(int h, int m, int s) : hour(h), minute(m), second(s) { normalize(); }
void setTime(int h, int m, int s) { hour=h; minute=m; second=s; normalize(); }
void tick() { second++; normalize(); }
void show() const { printf("%02d:%02d:%02d\n", hour, minute, second); }
~Time() { /* 釋放資源,若無動態資源可省略 */ }
private:
void normalize() {
minute += second / 60; second %= 60;
hour += minute / 60; minute %= 60;
hour %= 24;
}
};
class + private 數據;struct 僅用於無行為數據塊。const 正確性:只讀成員函數加 const。