慕课C++远征之离港篇(笔记)

一、C++引用

1、结构体中的引用

示例代码:

#include
using namespace std;
typedef struct
{
int x;
int y;
}Coor;
int main(void)
{
Coor c1;
Coor &c = c1;
c.x = 10;
c.y = 20;
cout<return 0;
}

//遇到的错误:LIBCD.lib(wincrt0.obj) : error LNK2001: unresolved external symbol _WinMain@

//解决方法: [Project] --> [Settings] --> 选择"Link"属性页, 在Project Options中将/subsystem:windows 改成/subsystem:console

2、指针引用

示例代码:

#include
using namespace std;
int main(void)
{
int a = 10;
int *p = &a; //p是a的引用,q是p的引用
int *&q = p;
*q = 20;
cout<<"a="<return 0;
}

3、引用作函数参数

示例代码:

//引用做函数参数
#include
using namespace std;
/*void fun(int *a,int *b)
{
int c = 0;
c = *a;
*a = *b;
*b = c;
}
int main(void)
{
int x = 10;
int y = 20;
fun(&x,&y);
cout<<"x = "<cout<<"y = "<return 0;
}*/
void fun(int &a,int &b)
{
int c = 0;
c = a;
a = b;
b = c;
}
int main(void)
{
int x = 10;
int y = 20;
fun(x,y);
cout<<"x = "<cout<<"y = "<return 0;
}

二、const关键字的使用

示例代码:

#include
#include
using namespace std;
//const 的使用
/*int main(void)
{
int x = 3;
int const *p = &x; //等价于const int *p = &x;
//*p = 5;  //错误
x = 5;     //正确

int y = 5;
int *const p = &x;  //const修饰p
//p = &y;   //错误
*p = 10;    //正确
cout<
int y = 5;
int const* p = &x;  //const修饰*
cout<<*p<p = &y;
cout<<*p<
//const修饰引用
int y = 5;
int const &z = x; //z为x的别名
// z = 10;//错误
cout<
system("pause");
return 0;
}*/

//const在函数中的应用
void fun(int &a,int &b)//正确
//void fun(int const &a,int const &b)//错误
{
a = 10;
b = 20;
}

int main(void)
{
int x = 3;
int y = 5;
fun(x,y);
cout<
system("pause");
return 0;
}

三、C++的新特性

示例代码:

//c++的新特性
#include
#include
using namespace std;

//内联函数

//函数参数的特性,赋值从右边开始
inline void fun(int i=10,int j=20,int k=30);
//函数重载
inline void fun(double i,double j);
int main(void)
{
/* //函数赋值
fun();
fun(100);//100覆盖i的值
fun(100,200);//100覆盖i,200覆盖j
fun(100,200,300);//100覆盖i,200覆盖j,300覆盖k
*/
//函数重载
fun(1.1,2.2);
fun(1,2);

system("pause");
return 0;
}

void fun(int i,int j,int k)
{
cout< }

void fun(double i,double j)
{
cout< }

四、C++内存管理

示例代码:

//内存申请和释放
#include
#include
using namespace std;
int main(void)
{
/* int *p = new int(20);

    //等价于
int *p = new int;
*p = 20;
*/
/*     //普通内存申请

int *p = new int;
if(p == NULL)
{
system("pause");
   return 0;
}
*p = 20;
cout<<*p<delete p; //普通内存释放
p = NULL;
*/

//申请块内存
int *p = new int[1000];
if(p == NULL)
{
system("pause");
   return 0;
}
p[0] = 100;
p[1] = 200;
cout<delete []p;//若写成delete p;则只是释放了p指向的第一个内存,后面999个内存无法释放
p = NULL;

system("pause");
return 0;
}

你可能感兴趣的:(C++学习)