Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ความแตกต่างระหว่าง Namespace และ Class ใน C++

namespace และ class เป็นคอนเซปต์ที่ต่างกันจริง แม้ทั้งคู่จะใช้จัดกลุ่มโค้ดได้

ความแตกต่างหลัก

ด้านNamespaceClass
ลักษณะกลุ่มชื่อ (name grouping)ชนิดข้อมูล (data type)
สร้างอินสแตนซ์ได้ไหมไม่ได้ได้ (object)
using directiveรองรับ (using namespace)ไม่รองรับ (ยกเว้น inheritance)
Reopen ได้ไหมได้ (ข้าม translation units)ไม่ได้ (definition ต้องครบในที่เดียว)
Unnamed ได้ไหมได้ (anonymous namespace)ไม่ได้ (compile error)
Access controlไม่มี (public เท่านั้น)มี (public/protected/private)
Inheritanceไม่มีรองรับ
Membersvariables, functions, classes, templatesdata members, member functions, constructors, operators

ตัวอย่าง: Namespace สามารถ Reopen ได้

// File1.cpp
namespace MyLib {
    void func1() { /* ... */ }
}

// File2.cpp
namespace MyLib {  // เปิด namespace เดิมต่อได้
    void func2() { /* ... */ }
}

// ใช้งาน
MyLib::func1();
MyLib::func2();

ตัวอย่าง: Class ไม่สามารถ Reopen ได้

// File1.cpp
class MyClass {
    void func1();  // Declaration only
};

// File2.cpp - ERROR: ไม่สามารถเพิ่ม member ได้
class MyClass {   // ❌ Compile error: redefinition
    void func2(); 
};

ตัวอย่าง: Unnamed Namespace vs Unnamed Class

// ✅ Unnamed namespace - OK (internal linkage)
namespace {
    int internalVar = 42;
    void helper() { /* ... */ }
}

// ❌ Unnamed class - ERROR
class {  // Compile error: unnamed class not allowed
    int x;
};

การใช้ using directive

namespace Math {
    const double PI = 3.14159;
    double square(double x) { return x * x; }
}

// ใช้ using namespace
using namespace Math;
cout << PI << endl;        // OK
cout << square(5) << endl; // OK

// Class: ต้องสร้าง object หรือใช้ static members
class MathClass {
public:
    static const double PI = 3.14159;
    static double square(double x) { return x * x; }
};

cout << MathClass::PI << endl;        // OK (static)
cout << MathClass::square(5) << endl; // OK (static)
// MathClass obj; obj.square(5);      // ต้องสร้าง object ถ้า non-static

สรุป: เมื่อไหร่ควรใช้อะไร?

  • Namespace: จัดกลุ่มฟังก์ชัน/ตัวแปร/คลาสที่เกี่ยวข้องกัน ป้องกัน name collision, library boundaries
  • Class: สร้างชนิดข้อมูลใหม่ ที่มี state (data) และ behavior (methods) รองรับ OOP (encapsulation, inheritance, polymorphism)