程式設計與演算法(三)C++面向物件程式設計 第一週 相關筆記
阿新 • • 發佈:2021-10-05
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; intmain(){ 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