文章目錄
- 目錄
- 一.存儲類
- 二.運算符
- 三.循環
- while
- for
- 四.判斷
目錄
一.存儲類
可見static存儲類修飾之后,i的值沒有從頭開始,而是從上一次的結果中保留下來
#include <iostream>using namespace std;
class Data
{
public:Data(){}~Data(){}void show(){cout<<this->data<<" "<<number<<endl;}static void showData()//先于類的對象而存在{//這方法調用的時候不包含this指針cout<<" "<<number<<endl;}private:int data;
public:static int number; //靜態數據在聲明時候類外初始化
};
int Data::number=0;//靜態成員初始化int main()
{Data::showData();//通過類名直接調用Data::number = 100;//通過類名直接使用Data d;d.show();d.showData();//通過對象調用cout << "Hello World!" << endl;return 0;
}
運行結果:
0
4197152 100
100
Hello World!
extern 修飾符通常用于多個文件共享的全局變量或函數的時候
二.運算符
#include <iostream>using namespace std;int main ()
{int var;int *ptr;int val;var = 3000;// 獲取 var 的地址ptr = &var;// 獲取 ptr 的值val = *ptr;cout << "Value of var :" << var << endl;cout << "Value of ptr :" << ptr << endl;cout << "Value of val :" << val << endl;return 0;
}
三.循環
while
for
基于范圍的for循環語句
#include <iostream>using namespace std;int main()
{int my_array[5] = {1, 2, 3, 4, 5};// 每個數組元素乘于 2for (int &x : my_array){x *= 2;cout << x << endl; }cout<<endl;// auto 類型也是 C++11 新標準中的,用來自動獲取變量的類型for (auto &x : my_array) {x *= 2;cout << x << endl; }
}
運行結果:
2
4
6
8
10
4
8
12
16
20
上面for述句的第一部分定義被用來做范圍迭代的變量,就像被聲明在一般for循環的變量一樣,其作用域僅只于循環的范圍。而在”:”之后的第二區塊,代表將被迭代的范圍。