C में struct और C++ में class
संबंधित state और behavior model करें।
C में struct और C++ में class क्या है?
C struct data group करता है; C++ class private state और methods से invariants बचाता है।
महत्वपूर्ण बातें
- Operations से पहले invariants तय करें।
- Empty, full और allocation-failure cases संभालें।
- Complexity और ownership साथ मापें।
C और C++ code examples
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 functions को struct pointer देता है। C++ class balance private रखकर valid methods से बदलता है।
C
Structures और operations अलग, allocation स्पष्ट होता है।
C++
Classes और containers invariants और resources manage करते हैं।
अभ्यास
दोनों versions चलाकर बदलें और language guarantees की तुलना करें।
- Empty और capacity boundary tests जोड़ें।
- Cleanup लागू कर leaks जाँचें।
- Standard container से तुलना करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज