C++ -- 第一次作业

运算符(sizeof 及 运算符的转换)

sizeof

sizeof 是一个关键字,它是一个编译时运算符,用于判断变量或数据类型的字节大小。
sizeof 运算符可用于获取类、结构、共用体和其他用户自定义数据类型的大小。
使用 sizeof 的语法如下:

  1. sizeof (data type);

实例:

  1. #include <iostream>
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6. cout << "Size of char : " << sizeof(char) << endl;
  7. cout << "Size of int : " << sizeof(int) << endl;
  8. cout << "Size of short int : " << sizeof(short int) << endl;
  9. cout << "Size of long int : " << sizeof(long int) << endl;
  10. cout << "Size of float : " << sizeof(float) << endl;
  11. cout << "Size of double : " << sizeof(double) << endl;
  12. cout << "Size of wchar_t : " << sizeof(wchar_t) << endl;
  13. return 0;
  14. }

运算结果:

  1. Size of char : 1
  2. Size of int : 4
  3. Size of short int : 2
  4. Size of long int : 4
  5. Size of float : 4
  6. Size of double : 8
  7. Size of wchar_t : 4

运算符的转换

运算符的优先级确定表达式中项的组合。这会影响到一个表达式如何计算。某些运算符比其他运算符有更高的优先级,例如,乘除运算符具有比加减运算符更高的优先级。
例如 x = 7 + 3 2,在这里,x 被赋值为 13,而不是 20,因为运算符 具有比 + 更高的优先级,所以首先计算乘法 3*2,然后再加上 7。

                                                                                        运算符的优先级
                                                低————————————————————————————>高
                                    char;    short;    int;    unsigned;    long;    unsigned long;    float;    double;

隐式转换

一些二元运算符要求两个操作数的类型一致,如不相同系统默认由低类型向高类型自动转换。

赋值运算中如等号两边类型不同,右值转换为左值类型.

显式转换(强制转换)

double x;               //将其转换为int 型。可用以下三种方法
int(x);    /    (int)x;    /    static cast \(x);

猜你喜欢

转载自www.cnblogs.com/ayanotc/p/11517917.html
今日推荐