ประวัติและลักษณะ
C++ พัฒนาโดย Bjarne Stroustrup ปี 1979 ที่ Bell Labs เป็น middle-level language รวมคุณสมบัติ high-level และ low-level เป็น superset ของ C โปรแกรม C ที่ถูกต้องเกือบทั้งหมดเป็น C++ ที่ถูกต้อง ทำงานบน Windows, Mac OS, UNIX ต่างๆ
ลักษณะสำคัญของ C++
- Statically typed: Type checking ตอน compile-time
- Compiled: แปลงเป็น machine code ก่อนรัน ไม่ใช่ interpreter
- General-purpose: ใช้ได้หลากหลายโดเมน ไม่เฉพาะทาง
- Case-sensitive: แยกตัวพิมพ์เล็ก-ใหญ่
- Free-form: ตำแหน่งตัวอักษรไม่สำคัญ
- Procedural Programming: โครงสร้างเป็น procedures/functions
- Object-oriented Programming (OOP): ใช้ objects ที่มี data และ methods
- Generic Programming: อัลกอริทึมเขียนในรูปแบบ types ที่ระบุภายหลัง (templates)
เริ่มต้นเรียน C++
1. ติดตั้ง C++ Compiler
- GCC: https://gcc.gnu.org/
- Clang: https://clang.llvm.org/get_started.html
- Visual C++ 2017 Community: https://www.visualstudio.com/vs/cplusplus/
- หรือใช้ online compiler: tutorialspoint.com/compile_cpp_online.php
2. เขียนโปรแกรมแรก (hello.cpp)
#include <iostream>
int main() {
std::cout << "Hello World\n";
}
3. Compile โปรแกรม
$ g++ -o hello hello.cpp
สร้าง executable ชื่อ hello จาก source hello.cpp
4. รันโปรแกรม
$ ./hello
ผลลัพธ์
Hello world