优秀的编程知识分享平台

网站首页 > 技术文章 正文

从c到c++入门(c到c++需要学多少)

nanyue 2024-08-10 18:36:10 技术文章 16 ℃

从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<<a<<endl;//输出为10 
 r1=b;
 cout<<a<<endl;//输出为5 
	return 0;
}

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:
	int w,h;
	int area(){
		return w*h;
	}
	int Perimeter(){
		return 2*(w+h);
	}
	void init(int w_,int h_){
		w = w_;h=h_;
	}
}; 
int main(){ //主函数
	int w,h;
	CRectangle r; //r是一个对象
	cin>>w>>h;
	r.init(w,h); 
	cout<<r.area()<<endl<<r.Perimeter();
	return 0;
}

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<<as[0]<<endl;
cout<<as[1]<<endl;
cout<<as[2]<<endl;
 
	return 0;
}

Tags:

最近发表
标签列表