输入输出
cout
<<流插入运算符
cin
>>流提取运算符
控制精度直接用c语言
printf("%.1f\n",j);
缺省参数
缺省
void Func(int a = 1)
{
cout << a << endl;
}
int main()
{
Func(2);
Func();
return 0;
}
结果:2
1
全缺省
注意:显示传参,只能从左往右
//全缺省
void Func1(int a = 10, int b = 20, int c = 30)
{
cout << "a =" << a << endl;
cout << "b =" << b << endl;
cout << "c =" << c << endl;
}
//调用方式
int main()
{
//显示传参,从左往右
Func1(1, 2, 3);
Func1(1);
Func1(1,2);
Func1();
return 0;
}
结果
半缺省
必须从右往左给缺省值
//半缺省
void Func2(int a , int b = 20, int c = 30)
{
cout << "a =" << a << endl;
cout << "b =" << b << endl;
cout << "c =" << c << endl;
}
int main()
{
Func2(1, 2, 3);
Func2(1, 2);
Func2(1);
return 0;
}
缺省参数有意义的场景
扩容
namespace wang
{
typedef struct Stack
{
int* a;
int top;
int capacity;
}ST;
void StackIntit(ST* ps,int N=4)
{
ps->a = (int*)malloc(sizeof(int*) * N);
ps->top=0;
int capacity = 0;
}
void StackPush(ST* ps, int x)
{
//......
}
}
缺省的应用,不知道的情况下默认4个
//100个
wang::ST st2;
StackIntit(&st2, 100);
for (size_t i = 0; i < 100; i++)
{
StackPush(&st2, i);
}
//不知道插入几个,用默认值4个
wang::ST st3;
StackIntit(&st3);
注意事项
1.半缺省参数必须从右往左依次来给出,不能间隔着给
2.缺省参数不能在函数声明和定义中同时出现
(不允许声明和定义同时给缺省参数)(声明给,定义不给)
声明
Stack.h
#pragma once
#include<stdlib.h>//找malloc
void StackIntit(ST* ps, int N = 4);
void StackPush(ST* ps, int x):
定义
#include"Stack.h"
void wang::StackIntit(ST* ps, int N )
{
ps->a = (int*)malloc(sizeof(int*) * N);
ps->top=0;
int capacity = 0;
}
void wang::StackPush(ST* ps, int x)
{
//......
}
连接冲突
预处理,编译
解决连接错误,要进行函数定义和声明分离
例子:创建一个Stack.cpp,导入Stack.h
因为两个文件里面都有StackIntit函数的定义,所以会发生冲突
解决1:声明定义分离
//声明(在Stack.h中)
void StackIntit(ST* ps, int N = 4);
//定义(在Stack.cpp中)
void wang::StackIntit(ST* ps, int N )
{
ps->a = (int*)malloc(sizeof(int*) * N);
ps->top=0;
int capacity = 0;
}
解决2:static
在全局可见,本质是进入符号表
static 只在当前文件可见,改变链接属性,从外部链接改为内部链接