โครงสร้างข้อมูลใน C/C++

struct ใน C และ class ใน C++

C struct รวมข้อมูล ส่วน C++ class ปกป้อง invariant ด้วย private state และ method

struct ใน C และ class ใน C++ คืออะไร?

C struct รวมข้อมูล ส่วน C++ class ปกป้อง invariant ด้วย private state และ method

สร้างโมเดล state และ behavior ที่เกี่ยวข้อง

ประเด็นสำคัญ

  • กำหนด invariant ก่อนเขียน operation
  • จัดการกรณีว่าง เต็ม และ allocation ล้มเหลว
  • ประเมิน complexity และ ownership พร้อมกัน

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <stdio.h>

typedef struct {
    const char *owner;
    double balance;
} Account;

void deposit(Account *account, double amount) {
    if (amount > 0) {
        account->balance += amount;
    }
}

int main(void) {
    Account account = {"Ada", 100.0};
    deposit(&account, 25.0);
    printf("%s: %.2f\n", account.owner, account.balance);
    return 0;
}
ผลลัพธ์ที่คาดหวัง
Ada: 125.00
C++
รันโค้ด →
main.cpp
#include <iomanip>
#include <iostream>
#include <string>
#include <utility>

class Account {
    std::string owner_;
    double balance_;

public:
    Account(std::string owner, double balance)
        : owner_(std::move(owner)), balance_(balance) {}

    void deposit(double amount) {
        if (amount > 0) {
            balance_ += amount;
        }
    }

    void print() const {
        std::cout << owner_ << ": " << std::fixed
                  << std::setprecision(2) << balance_ << '\n';
    }
};

int main() {
    Account account("Ada", 100.0);
    account.deposit(25.0);
    account.print();
}
ผลลัพธ์ที่คาดหวัง
Ada: 125.00

เปรียบเทียบ C และ C++

C ส่ง struct pointer ให้ฟังก์ชัน ส่วน C++ เก็บ balance เป็น private และแก้ผ่าน method ที่ถูกต้อง

C

Struct และ operation แยกกัน การจัดสรรชัดเจน

C++

Class และ container รักษา invariant และ resource

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • ทดสอบสถานะว่างและเต็ม
  • เขียน cleanup และตรวจ memory leak
  • เปรียบเทียบกับ standard container