前言:更多内容请看总纲《嵌入式C/C++学习路》
#include
using namespace std;
void foo(int a, char b, float c = 4.56f, const char *d = "Hello C++ !")
{
cout << a << ' ' << b << ' ' << c << ' ' << d << endl;
}
void bar(int x = 666); // 在声明中定义缺省参数
int main(void)
{
foo(10, 'A', 1.23f, "Hello world!");
foo(10, 'A', 1.23f); // 缺省
foo(10, 'A'); // 缺省
bar(); // 缺省
return 0;
}
void bar(int x)
{ // 这是函数定义,声明在main上面,在声明里定义缺省参数
cout << x << endl;
}
#include
using namespace std;
void foo(int){ // 哑元参数
cout << "foo(int)" << endl;
}
int main(void){
foo(10);
return 0;
}
int pi = new int;
delete pi;
int *pi = new int (100);
int *pi = new int[ 4 ]{1,2};
delete[] pi;
#include
using namespace std;
int main()
{
int *p1 = new int;
*p1 = 1234;
cout << *p1 << endl;
delete p1;
p1 = new int(1000); // 带初值
cout << *p1 << endl;
delete p1;
p1 = new int[4]{10, 20, 30, 40}; // 如果不赋初值,默认为0
cout << p1[0] << ' ' << p1[1] << ' ' << p1[2] << ' ' << p1[3] << endl;
delete[] p1; // 记得加中括号
return 0;
}
int (*prow)[4] = new int [3][4]; // 二维数组的首地址是一维数组
int (*ppage)[4][5] = new int [3][4][5]; // 三维数组的首地址是二维
new(指针)类型(初值);
在一个已分配的内存空间中创建对象
#include
using namespace std;
int main()
{
int *p1 = new int;
*p1 = 1234;
cout << *p1 << endl;
delete p1;
p1 = new int(1000); // 带初值
cout << *p1 << endl;
delete p1;
p1 = new int[4]{10, 20, 30, 40}; // 如果不赋初值,默认为0
cout << p1[0] << ' ' << p1[1] << ' ' << p1[2] << ' ' << p1[3] << endl;
delete[] p1;
int (*p2)[4] = new int[3][4]{{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
for (size_t i = 0; i < 3; i++)
{
for (size_t j = 0; j < 4; j++)
{
cout << p2[i][j] << ' ';
}
cout << endl;
}
delete[] p2;
return 0;
}
#include
using namespace std;
int main()
{
int *p1 = new int;
*p1 = 1234;
cout << *p1 << endl;
delete p1;
p1 = new int(1000); // 带初值
cout << *p1 << endl;
delete p1;
p1 = new int[4]{10, 20, 30, 40}; // 如果不赋初值,默认为0
cout << p1[0] << ' ' << p1[1] << ' ' << p1[2] << ' ' << p1[3] << endl;
delete[] p1;
int(*p2)[4] = new int[3][4]{{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
for (size_t i = 0; i < 3; i++)
{
for (size_t j = 0; j < 4; j++)
{
cout << p2[i][j] << ' ';
}
cout << endl;
}
delete[] p2;
short buf[4]; // 在栈里面不需要释放内存
p1 = new(buf) int(0x12345678);
cout << showbase << hex << *p1 << endl; // showbase打印前缀 hex是16进制
cout << buf[0] << ' ' << buf[1] << endl; // 内存地址重叠
return 0;
}