從c到c++入門

從c到c++

1.引用

(數據類型)&變量1=變量2

例如:int &a =b;

#include <iostream>
using namespace std;
int main(){
int a=4,b=5;
int &r1=a;
int &r2=r1;
r2=10;
cout</<iostream>

2.常引用(在引用前加const關鍵字)

int n;
const int & r = n;

2.const關鍵字

1.定義常量

const int PI 3.14

2.常量指針

不能通過常量指針修改其指向的內容

3.動態內存

1.new分配內存 :new 的返回值是地址

int *p
p = new int;
*p = 5;

2.數組內存分配

 int *pn; 

int i=5;
pn =new int[i*20];
pn[0]=20;
pn[100]=30;/編譯沒問題數組越界

2.delete釋放內存

int *p;
*p = 5;
delete p;
delete p;//導致異常,不能重複釋放

3.釋放數組內存

int *p = new int[20];
p[0]=1;
delete []p;//✨

4.函數

1.內聯函數(inline 關鍵字)

2.函數重載

int MAX(int a,int b);
int MAX(double a,double b);
int MAX(int a,int b,int c);

3.函數缺省參數(程序的可擴充性)

int FUNC(int x,int y=2,int z=3);
//注:只能最右邊連續若干個參數缺省

5.類和對象

1.結構程序化設計(過於繁瑣) 程序=數據結構+算法

2.面向對象程序設計 程序=類+類+類+... ...

//寫一個程序,輸入矩形的長和寬,輸出矩形的面積和周長
#include <iostream> //頭文件
using namespace std;
class CRectangle{ //類
public:
\tint w,h;
\tint area(){
\t\treturn w*h;
\t}
\tint Perimeter(){
\t\treturn 2*(w+h);
\t}
\tvoid init(int w_,int h_){
\t\tw = w_;h=h_;
\t}
};
int main(){ //主函數
\tint w,h;
\tCRectangle r; //r是一個對象
\tcin>>w>>h;
\tr.init(w,h);
\tcout<<r.area>\treturn 0;
}
/<r.area>/<iostream>

3.類的其他用法

用法2.指針->成員名
CRectangle r1,r2;
CRectangle p1=&r1;
CRectangle* p2=&r2;
p1->w=5;
p2->nit(5,4);//nit作用在p2指向的對象上
用法3:引用名.成員名
REctangle r2;
CRectangle rr=r2;
rr.w=5;
rr.Init(5, 4);

//xx的值變了,x2的值也變

6.定義string對象

string str1;//定義string對象

string city = "beijing";//定義string對象並對其初始化

#include <iostream>
using namespace std;
int main(){
string str1;
string as[]={"beijing","shanghai","chengdu"};//string數組的每一項存的是一個字符串
cout<cout<cout<
\treturn 0;
}
/<iostream>


分享到:


相關文章: