1、引用
#include<bits/stdc++.h> using namespace std; void swap(int &a,int &b){ int temp = a; a = b; b = temp; } void swap(int *a,int *b){ int temp = *a; *a = *b; *b = temp; } int main(){ int a = 1,b = 2; swap(a,b); cout<<a<<" "<<b<<endl; swap(&a,&b); cout<<a<<" "<<b<<endl; }
#include<bits/stdc++.h> using namespace std; int n = 1; int & set_value(){return n;} int main(){ set_value() = 2; cout<<n<<endl; }
2、const关键字
#include<bits/stdc++.h> using namespace std; int main(){ int a = 1; const int & b = a; b = 2; cout<<a<<endl; } [Error] assignment of read-only reference 'b'
#include<bits/stdc++.h> using namespace std; int main(){ int a = 1; const int & b = a; a = 2; cout<<a<<endl; } 输出:2
cont int * 不能改变该位置的值,但可以换位置
3、动态内存分配
#include<bits/stdc++.h> using namespace std; int main(){ int * p = new int ; *p = 2; cout<<*p<<endl; delete p; cout<<*p<<endl; } 2 8526352
#include<bits/stdc++.h> using namespace std; int main(){ int * p = new int [10]; p[1] = 1; cout<<p[1]<<endl; delete [] p ; } 1
4、内联函数和数参数缺省值
#include<bits/stdc++.h> using namespace std; inline int max(int a,int b){ return a>b?a:b; } inline double max(double a,double b){ return a>b?a:b; } inline int max(int a,int b,int c){ return a>b?max(a,c):max(b,c); } inline void g(int a,int b = 1){ cout<<a<<" "<<b<<endl; } int main(){ cout<<max(1,2)<<" "<<max(1.2,1.3)<<" "<<max(1,2,3)<<endl; g(3); } 2 8526352
5、类和对象的基本概念与用法(1)
面向对象 = 类 + 类 + 类 + 类 + 类 + 类 + 类 + 类......
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #include<bits/stdc++.h> using namespace std; class rectangle{ public: int w,h; void init(int _w,int _h){ w = _w; h = _h; } void area(){ cout<<w*h<<endl; } void perimeter(){ cout<<(w+h)*2<<endl; } }; int main(){ rectangle r; r.init(1,2); r.area(); r.perimeter(); rectangle &r2 = r; r2.area(); rectangle *r3 = &r; r3->area(); return 0; } 2 6 2 2
不加public 默认private