C++學習總結(四)

一.new delete用法

int *p=new int[80];//通過new申請內存空間
int (*px)[10]=((int *)[10])p;
1.new只能分配線性內存。

2.基本數據類型可以直接delete,複雜的如,數組,對象數組應包含delete []p;  delete只能釋放一次,釋放後指向一個安全的地址。

二.函數重載原理

1.函數重載根據,參數類型不同,順序不同,與返回值無關。函數名委託代理,根據不同的參數委託不同的函數。

void go(int,int){}
void go(int,double){}
void go(double){}

 

#include<iostream>
#include<stdlib.h>
using namespace std;
void go(int a)
{
	cout << a << endl;
}
void go(double a)
{
	cout << a << endl;
}
void go(int a, int b)
{
	cout << a << ' ' << b << endl;
}

void main()
{
	void (*p1)(int) = go;
	void (*p2)(double) = go;
	void (*p3)(int, int) = go;

	cout << p1 << endl;
	cout << p2 << endl;
	cout << p3 << endl;

	system("pause");
}

2.函數的默認參數

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
void print(int c,int a = 1, int b = 3)//c語言不可以這樣
{
	cout << a <<b<<c<<endl;
}
void print(int d)
{
	cout << d<<endl;
}

void main()
{   
	void (*p1)(int c,int a,int b) = print;
	void (*p2)(int) = print;
	p1(5,1,3);
	p2(5);
	system("pause");
}


三.auto類型

1.auto實現通用的傳入接口,根據變量類型進行定義。

2.對於auto變量的類型可通過函數 typeid().name() 獲得。

#include<iostream>
#include<stdlib.h>
void main()
{
	double db = 10.9;
	double *pdb = &db;
	auto num = pdb;//通用傳入接口
	std::cout << typeid(db).name() << std::endl;//打印變量數據類型
	std::cout << typeid(num).name() << std::endl;
	std::cout << typeid(pdb).name() << std::endl;
    
	//typeid(db).name() db2;
	decltype(db) numA(10.8);//通用的備份接口
	std::cout << sizeof( numA )<<' '<<numA<< std::endl;
	system("pause");
}
3.auto用於for循環中進行數組讀取

#include<iostream>
#include<stdio.h>
using namespace std;
void main()
{
	auto num(10);
	auto num1(10.9);
	cout << num << ' ' << num1 << endl;
	
	int num2[10] = { 1,2,3,4,5,6,7,8,9,10 };
	for (auto data : num2)//循環一維數組
	{
		cout << data << endl;
	}
	double db[2][5] = { 1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9,10.10 };
	for (auto data : db)
	{
		cout << data << endl;
		for (int i=0;i < 5;i++)
		{
			cout << *(data + i) << endl;
		}
	}
	getchar();

四.枚舉類型enum

1.C語言中的enum類型不注重類型。

#include<stdio.h>
enum color { red=11, yellow, green, white };
void main1()
{   
	enum color color1;
	color1 = red;// 不注重數據類型
	color1 = 11;
	printf("%d\n", red);
	printf("%d\n",yellow);
	printf("%d\n", green);
	getchar();
}
2.C++中enum可以限定類型通過enum類型限定爲char

#include<iostream>
#include<stdlib.h>
enum color:char{red,yellow,green,white};//限定枚舉的數據類型
void main()
{
	color mycolor(red);
	color mycolor1(color::red);
	//mycolor = 1;//fault錯誤的賦值方式,類型不匹配
	//mycolor = 'A';
	mycolor = color::yellow;
	printf("%d,%c\n", red);
	printf("%d,%c\n", yellow);

	system("pause");
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章