为什么 sizeof() 在 C++ 中实现为运算符?

sizeof 不是 C++ 中的真正运算符。它只是插入一个等于参数大小的连续字符的特殊语法。sizeof 不需要或没有任何运行时支持。Sizeof 不能重载,因为内置操作(例如将指针增加到数组中)隐式依赖于它。

C 标准指定 sizeof 应作为运算符实现。在大多数编译器中,sizeof 的值在编译时被一个等于它的常量替换。

例子

#include <iostream>
using namespace std;
int main() {
   cout << "字符大小: " << sizeof(char) << endl;
   cout << "int 的大小: " << sizeof(int) << endl;
   cout << "短整数的大小: " << sizeof(short int) << endl;
   cout << "long int 的大小: " << sizeof(long int) << endl;
   cout << "浮标尺寸: " << sizeof(float) << endl;
   cout << "双人尺寸: " << sizeof(double) << endl;
   cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
   return 0;
}
输出结果

这将给出输出 -

字符大小: 1
int 的大小: 4
短整数的大小: 2
long int 的大小: 4
浮标尺寸: 4
双人尺寸: 8
Size of wchar_t : 4