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

ทำไม sizeof() ถูก implement เป็น operator ใน C++


ข้อเท็จจริงสำคัญ

sizeof ไม่ใช่ operator จริงๆ ใน C++ มันเป็น special syntax เท่านั้น ที่แทรกค่าคงที่เท่ากับขนาดของ argument ไม่ต้องการ runtime support ใดๆ

เหตุผลที่ไม่สามารถ overload ได้

Built-in operations เช่นการเพิ่ม pointer เข้า array อย่างนัยสำคัญพึ่งพา sizeof การ overload จะทำลายพฤติกรรมพื้นฐานนี้

มาตรฐาน C

มาตรฐาน C ระบุว่า sizeof ควร implement เป็น operator ในคอมไพเลอร์ส่วนใหญ่ ค่าของ sizeof จะถูกแทนที่ด้วยค่าคงที่ใน compile time

ตัวอย่าง

#include <iostream>
using namespace std;

int main() {
    cout << "Size of char: " << sizeof(char) << endl;
    cout << "Size of int: " << sizeof(int) << endl;
    cout << "Size of short int: " << sizeof(short int) << endl;
    cout << "Size of long int: " << sizeof(long int) << endl;
    cout << "Size of float: " << sizeof(float) << endl;
    cout << "Size of double: " << sizeof(double) << endl;
    cout << "Size of wchar_t: " << sizeof(wchar_t) << endl;
    return 0;
}

ผลลัพธ์ (ตัวอย่างบนระบบ 64-bit ทั่วไป)

Size of char: 1
Size of int: 4
Size of short int: 2
Size of long int: 4
Size of float: 4
Size of double: 8
Size of wchar_t: 4

หมายเหตุ: ขนาดอาจแตกต่างไปตาม platform และ compiler