运算符是一个符号,用于指示编译器以编程语言执行某些操作。
alignof运算符是返回要应用于给定变量类型的对齐方式的运算符。返回的值以字节为单位。
var align = alignof(tpye)
alignof-运算符用于返回输入数据的对齐方式。
参数类型-要返回其对齐方式的数据类型。
返回值-用作给定数据类型的对齐方式的值(以字节为单位)。
该程序返回用于对齐基本数据类型的值。
#include <iostream> using namespace std; int main(){ cout<<"Alignment of char: "<<alignof(char)<< endl; cout<<"Alignment of int: "<<alignof(int)<<endl; cout<<"Alignment of float: "<<alignof(float)<< endl; cout<<"Alignment of double: "<<alignof(double)<< endl; cout<<"Alignment of pointer: "<<alignof(int*)<< endl; return 0; }
输出结果
Alignment of char: 1 Alignment of int: 4 Alignment of float: 4 Alignment of double: 8 Alignment of pointer: 8
#include <iostream> using namespace std; struct basic { int i; float f; char s; }; struct Empty { }; int main(){ cout<<"Alignment of character array of 10 elements: "<<alignof(char[10])<<endl; cout<<"Alignment of integer array of 10 elements: "<<alignof(int[10])<<endl; cout<<"Alignment of float array of 10 elements: "<<alignof(float[10])<<endl; cout<<"Alignment of class basic: "<<alignof(basic)<<endl; cout<<"Alignment of Empty class: "<<alignof(Empty)<<endl; return 0; }
输出结果
Alignment of character array of 10 elements: 1 Alignment of integer array of 10 elements: 4 Alignment of float array of 10 elements: 4 Alignment of class basic: 4 Alignment of Empty class: 1
的sizeof()操作者在C ++编程语言是用于计算尺寸的一元运算符的操作数。
该程序将显示sizeof运算符和alignof运算符之间的区别。
#include <iostream> using namespace std; int main(){ cout<<"Alignment of char: "<<alignof(char)<<endl; cout<<"size of char: "<<sizeof(char)<<endl; cout<<"Alignment of pointer: "<<alignof(int*)<<endl; cout<<"size of pointer: "<<sizeof(int*)<<endl; cout<<"Alignment of float: "<<alignof(float)<<endl; cout<<"size of float: "<<sizeof(float)<<endl; return 0; }
输出结果
Alignment of char: 1 size of char: 1 Alignment of pointer: 8 size of pointer: 8 Alignment of float: 4 size of float: 4