引用的基本用法
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int &b = a;
b = 100;
cout << a <<endl;
int a1[5] = {1, 2, 3, 4, 5};
int (&arr)[5] = a1;
// 另外一种写法
// typedef int ARR[5];
// ARR &arr = a1;
for(int i=0; i<5; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
#include <iostream>
#include <stdlib.h>
using namespace std;
// 指针方式,进行交换变量
void swap(int *x, int *y)
{
int tmp = *x;
*x = *y;
*y = tmp;
}
void test01()
{
int a= 10;
int b= 20;
swap(&a, &b);
cout << a << " " << b<< endl;
}
// 函数的引用方式,进行交换变量
void swap_ref(int &x, int &y)
{
int tmp = x;
x = y;
y = tmp;
}
void test02()
{
int a= 10;
int b= 20;
swap_ref(a, b);
cout << a << " " << b<< endl;
}
void get_mem(int **q)
{
*q = (int *)malloc(5 * sizeof(int));
}
void get_mem_ref(int * &q)
{
q = (int *)malloc(5 * sizeof(int));
}
void tes03()
{
int *p = NULL;
get_mem(&p);
get_mem_ref(p);
}
int main()
{
test01();
test02();
tes03();
return 0;
}
内联函数
为什么要有内联函数
1、宏看起来像是一个函数调用,会有隐藏的一些难以发现的错误
2、在c++里面,预处理器不允许访问类的成员,也就是说预处理器宏不能用作类的成员函数
内联函数就是继承了宏函数的高效,并且不会出错,还可以当成类的成员函数用
宏函数和内联函数的区别
宏函数的替换是发生在预处理阶段
内联函数的替换是发生在编译阶段
宏函数容易出错,内联函数不会
内联函数和宏函数,都省去了调用函数的开销(比如形参的替换等等)
#include <iostream>
using namespace std;
#define MYADD(a,b) a+b
// #define MYADD(a,b) (a+b) // 这里可以(a+b)解决此问题
// 这是个内联函数
inline int myadd(int a, int b)
{
return a+b;
}
void test01()
{
int a= 10;
int b= 20;
// int c = MYADD(a,b)*5; // 替换发生在预处理阶段 10 + 20 *5 = 110
int c = myadd(a, b)*5; // 替换发生在编译阶段 (10+20) *5 = 150
cout << c << endl;
}
int main()
{
test01();
return 0;
}
#include <iostream>
using namespace std;
#define MYCOMPARE(a,b) a<b?a:b
// 这是个内联函数
inline int mycompare(int a, int b)
{
return a < b ? a : b;
}
void test01()
{
int a= 1;
int b= 5;
int c = MYCOMPARE(++a,b); // 替换发生在预处理阶段 ++a < b ? ++a :b 这里的结果是3
// int c = mycompare(++a, b); // 替换发生在编译阶段 这里结果是2
cout << c << endl;
}
int main()
{
test01();
return 0;
}
externC
test.h
#pragma once
#if __cplusplus
extern "C" {
#endif
int myadd(int a, int b);
#if __cplusplus
}
#endif
test.c
int myadd(int a, int b)
{
return a+b;
}
main.cpp
#include <iostream>
#include "test.h"
using namespace std;
int main()
{
cout << myadd(2, 3) << endl;
return 0;
}
struct结构体
c++结构体里面可以放函数,c里面不行
#include <iostream>
#include <string.h>
using namespace std;
struct student
{
int age;
int id;
char name[256];
void print() // c++结构体里面可以放函数,c里面不行
{
cout << age <<" " << id << " " << name << endl;
}
};
void test01()
{
student obj;
obj.age = 10;
obj.id = 20;
strcpy(obj.name, "lucy");
obj.print(); // 10 20 lucy
}
int main()
{
test01();
return 0;
}