C++ เพิ่มแนวคิด OOP และ generic programming จาก C เหมาะสำหรับงานระบบ เกม และโปรแกรมที่ต้องการประสิทธิภาพสูง
C++ เป็นภาษา compiled ที่เพิ่ม OOP, templates และ STL จาก C ทำให้มีทั้งประสิทธิภาพสูงและความสามารถในการเขียนโค้ดที่ซับซ้อน
Unreal Engine, Unity (native)
OS, Drivers, Browsers
High-frequency trading
Arduino, Robotics
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
// หรือใช้ namespace
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}# macOS xcode-select --install # or brew install gcc # Linux (Ubuntu) sudo apt install g++ # Windows # ติดตั้ง MinGW-w64 หรือ Visual Studio
# คอมไพล์พื้นฐาน g++ main.cpp -o main # ระบุ C++ version (แนะนำ C++17 ขึ้นไป) g++ main.cpp -std=c++17 -o main # พร้อม warnings และ optimization g++ main.cpp -std=c++17 -Wall -Wextra -O2 -o main # รัน ./main # macOS/Linux main.exe # Windows
#include <iostream>
#include <string>
using namespace std;
int main() {
// Output
cout << "Hello World" << endl;
cout << "Number: " << 42 << endl;
// Input
int age;
cout << "Enter age: ";
cin >> age;
string name;
cout << "Enter name: ";
cin >> name; // อ่านถึง whitespace
// อ่านทั้งบรรทัด
cin.ignore(); // clear buffer
string fullName;
cout << "Enter full name: ";
getline(cin, fullName);
return 0;
}#include <iomanip> double pi = 3.14159265; // ทศนิยม cout << fixed << setprecision(2) << pi << endl; // 3.14 // ความกว้าง cout << setw(10) << "Hello" << endl; // " Hello" // เลขฐาน cout << hex << 255 << endl; // ff cout << oct << 255 << endl; // 377 cout << dec << 255 << endl; // 255
// Integer types int age = 20; long bigNum = 1000000L; long long veryBig = 10000000000LL; unsigned int positive = 100; // Floating point float f = 3.14f; double d = 3.14159265; // Boolean bool active = true; bool done = false; // Character char grade = 'A'; char newline = '\n'; // String (from <string>) #include <string> string name = "Somchai"; string greeting = "Hello, " + name;
// auto - ให้ compiler อนุมาน type auto x = 10; // int auto y = 3.14; // double auto s = "hello"s; // string (C++14) // const - ค่าคงที่ const int MAX = 100; const double PI = 3.14159; // constexpr - compile-time constant (C++11) constexpr int SIZE = 10; // nullptr แทน NULL (C++11) int* ptr = nullptr;
int score = 85;
if (score >= 80) {
cout << "Grade: A" << endl;
} else if (score >= 70) {
cout << "Grade: B" << endl;
} else {
cout << "Grade: C" << endl;
}
// switch
int day = 3;
switch (day) {
case 1: cout << "Mon"; break;
case 2: cout << "Tue"; break;
case 3: cout << "Wed"; break;
default: cout << "Other";
}// for loop
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
// while loop
int count = 0;
while (count < 3) {
cout << count++ << endl;
}
// Range-based for (C++11)
vector<int> nums = {1, 2, 3, 4, 5};
for (int n : nums) {
cout << n << " ";
}
// with reference (modify)
for (int& n : nums) {
n *= 2;
}