c++基础语法

当当当当!

时间过的真的好快,C语言已经学完了,开始学c++了,博客也没有坚持写,新阶段新开始嘛,希望能按时写奥!

  • 命名空间

       作用域:不可以在同一个作用域下声明两个相同名字的变量

 1 #include <iostream>
 2 using namespace std;
 3 int age = 300;//注释掉这行
 4 namespace Person
 5 {
 6     int age = 200;
 7 }
 8 namespace Bird
 9 {
10     int age = 100;
11     int sex = 101;
12 }
13 using namespace Bird;
14 int main()
15 {
16     cout<<::age<<endl;//查看这行变化   全局变量优先级高
17     cout<<Person::age<<endl;
18     cout<<Bird::age<<endl;
19     cout<<::sex<<endl;
20 }
  • new delete
 1 #include <iostream>
 2 using namespace std;
 3 int main()
 4 {
 5     int *p = new int;
 6     *p = 10;
 7     cout<<*p<<endl;
 8     delete p;
 9     p = 0;
10 
11     int *arr = new int[10];
12     arr[0] = 0;
13     arr[1] = 1;
14     cout<<arr[0]<<" "<<arr[1]<<endl;
15     cout<<arr<<endl;
16     delete[] arr;//delete 数组要加[]
17     //cout<<arr<<endl;
18     //delete之后指针还指向地址,但该空间已经不属于我,不要对它进行操作!
19     arr = 0;
20 
21     int *a = new int(10);//将a指向的int初始化为10
22     cout<<*a<<endl;
23     delete a;
24     a = 0;
25 }
  • 缺省函数参数
 1 #include <iostream>
 2 using namespace std;
 3 
 4 void Show(int a ,int b , int c = 2, int d = 3);
 5 int main()
 6 {
 7     Show(100,200);
 8     int arr[10] = {0,1,2,3,4,5,6,7,8,9};
 9 }
10 //不能再函数实现中加参数,如果函数声明中已存在则重复定义,如果没有则格式错误
11 void Show(int a  ,int b , int c  , int d )
12 {
13     cout << a << " " << b <<endl;
14     cout << c << " " << d <<endl;
15 }
  • for循环

1 for(auto i : arr)//auto可自动识别arr中类型
2 {
3     cout<< i << " ";
4 }
  •  函数重载

函数名相同,函数参数个数或类型不同

  • 引用

值传递,地址传递和引用

 1 #include <iostream>
 2 using namespace std;
 3 void Num(int a,int b);
 4 void Adress(int *a,int *b);
 5 void Yinyong(int &aa, int &bb);
 6 int main()
 7 {
 8     int a = 5;
 9     int b = 6;
10     cout<<a<<" "<< b<<endl;
11     Num(a,b);
12     cout<<a<<" "<< b<<endl;
13     Adress(&a,&b);
14     cout<<a<<" "<< b<<endl;
15     Yinyong(a,b);
16     cout<<a<<" "<< b<<endl;
17 
18 }
19 void Num(int a,int b)
20 {
21     int c;
22     c = a;
23     a = b;
24     b = c;
25 }
26 void Adress(int *a,int *b)
27 {
28     int c = *a;
29     *a = *b;
30     *b = c;
31 }
32 void Yinyong(int &a, int &b)
33 {
34     int c;
35     c = a;
36     a = b;
37     b = c;
38 }
原文地址:https://www.cnblogs.com/Lune-Qiu/p/7878574.html