命名空间
//命名空间:namespace
//定义一个命名空间
//含义:规定作用域
#include <stdio.h>
#include <windows.h>
namespace N1{
int a=10;
int b = -1;
int add(){
return a + b;
}
}
using N1::b;
using namespace N1;
//命名空间的使用
int main(){
//使用方法一
printf("a+b=%d\n",N1::add());
//使用方法二:using N1::b;
printf("b=%d\n", b);
//使用方法三:using namespace N1;
printf("a=%d\n", a);
system("pause");
return 0;
}
缺省函数
定义:声明或定义函数时为函数的参数指定一个默认值。在调用该函数时,如果没有指定实参则采用该默认值,否则使用指定的实参。
//C++的输入输出
#include<iostream>//必须
using namespace std;//必须
int add1(int a=0,int b=20){//全缺省参数
return a + b;
}
int add2(int a,int b=10){//半缺省参数
//对于半缺省参数:在函数声明和函数定义同时出现时,如果缺省值不同,编译器则不能确认该用哪个默认值,并且,缺省值是从右往左依次赋值
return a + b;
}
int main(){
int a,b;
cin >> a >> b;//标准输入
cout <<a<<"+"<<b<<"="<<a + b << endl;
cout << "hello,世界" << endl;//自带换行
cout << add1() << endl;
cout << add1(1) << endl;
cout << add1(1, 2) << endl;
cout << add2(1) << endl;
system("pause");
return 0;
}
函数重载
函数名相同,参数列表不同。
#include<iostream>
using namespace std;
//函数重载:函数名相同,参数列表不同
void show(){
cout << "哈哈哈啊哈哈" << endl;
}
void show(char* str){
cout << str << endl;
}
int main(){
show();
show("啦啦啦啦啦");
system("pause");
return 0;
}