目录
一.存储类
可见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};
// 每个数组元素乘于 2
for (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循环的变量一样,其作用域仅只于循环的范围。而在”:”之后的第二区块,代表将被迭代的范围。