C++ sizeof 运算符
sizeof 是一个关键字,但它是一个编译时运算符,用于确定变量或数据类型的大小(以字节为单位)。
sizeof 运算符可用于获取类、结构体、联合体以及任何其他用户定义数据类型的大小。
sizeof 运算符的语法
使用 sizeof 的语法如下:
sizeof (数据类型)
其中 data type 是所需的数据类型,包括类、结构体、联合体以及任何其他用户定义数据类型。
sizeof 运算符示例
尝试以下示例以了解 C++ 中所有可用的 sizeof 运算符。将以下 C++ 程序复制并粘贴到 test.cpp 文件中,然后编译并运行该程序。
#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; }
当上述代码被编译并执行时,它会产生以下结果,该结果可能因机器而异 -
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
更多 C++ 中 sizeof 的示例
以下示例演示了 C++ 中 sizeof
运算符的常见用法:
查找不同变量的大小
在以下示例中,我们将查找不同变量占用的内存大小。
#include <iostream> using namespace std; int main() { int age = 25; float price = 99.99; char grade = 'A'; // 打印变量的大小 cout << "Size of age (int): " << sizeof(age) << " bytes" << endl; cout << "Size of price (float): " << sizeof(price) << " bytes" << endl; cout << "Size of grade (char): " << sizeof(grade) << " bytes" << endl; return 0; }
执行时,该程序输出:
Size of age (int): 4 bytes Size of price (float): 4 bytes Size of grade (char): 1 bytes
使用 sizeof 查找数组的大小
在下面的示例中,我们将查找整数数组的总大小及其包含的元素数量。
#include <iostream> using namespace std; int main() { int scores[] = {85, 90, 78, 92, 88}; // 查找数组中的元素数量 int totalSize = sizeof(scores); int elementSize = sizeof(scores[0]); int length = totalSize / elementSize; cout << "Total size of array: " << totalSize << " bytes" << endl; cout << "Size of one element: " << elementSize << " bytes" << endl; cout << "Number of elements: " << length << endl; return 0; }
执行时,该程序输出:
Total size of array: 20 bytes Size of one element: 4 bytes Number of elements: 5
查找类的大小
在下面的示例中,我们将查找某个类的对象所占用的内存大小。
#include <iostream> using namespace std; class Student { int rollNumber; double marks; public: Student(int r = 1, double m = 95.5) : rollNumber(r), marks(m) {} }; int main() { // Finding size of class Student cout << "Size of Student class: " << sizeof(Student) << " bytes" << endl; return 0; }
执行时,该程序输出:
Size of Student class: 16 bytes