struct trong C và class trong C++
C struct nhóm dữ liệu; C++ class kết hợp private state và member function để bảo vệ invariant.
struct trong C và class trong C++ là gì?
C struct nhóm dữ liệu; C++ class kết hợp private state và member function để bảo vệ invariant.
Mô hình hóa state và behavior liên quan.
Điểm quan trọng
- Xác định invariant trước khi cài đặt operation.
- Xử lý trường hợp rỗng, đầy và cấp phát thất bại.
- Đánh giá đồng thời complexity và ownership.
Code ví dụ bằng C và 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
So sánh C và C++
C truyền struct pointer cho function; C++ giữ balance private và chỉ thay đổi qua method hợp lệ.
C
Struct và operation thường tách rời, cấp phát được quản lý thủ công.
C++
Class và container có thể bảo vệ invariant và tự quản lý tài nguyên.
Bài tập mở rộng
Chạy cả hai phiên bản rồi thay đổi để quan sát khác biệt về bảo đảm của từng ngôn ngữ.
- Thêm test cho trạng thái rỗng và capacity boundary.
- Cài đặt cleanup rồi kiểm tra memory leak.
- So sánh complexity với standard container.