namespace 用法
#include <iostream>
namespace China // 1
{
double population = 14.5;
double GDP = 17.8;
namespace Shanghai // 2
{
double population = 0.56;
double GDP = 1.25;
}
}
namespace USA
{
double population = 3.25;
double GDP = 25.4;
namespace NewYork
{
double population = 0.32;
double GDP = 2.34;
}
}
namespace Japan
{
double population = 1.1;
double GDP = 8.3;
namespace Tokyo
{
double population = 0.43;
double GDP = 1.9;
}
}
using namespace Japan; // 3
using std::cout; //4
int main()
{
cout << "中国的人口与经济总量:" << std::endl; //5
cout << China::population << " " << China::GDP << std::endl; // 6
cout << "中国上海的人口与经济总量:" << std::endl;
cout << China::Shanghai::population << " " << China::Shanghai::GDP << std::endl; //7
cout << "美国的人口与经济总量:" << std::endl;
cout << USA::population << " " << USA::GDP << std::endl;
cout << "美国纽约的人口与经济总量:" << std::endl;
cout << USA::NewYork::population << " " << USA::NewYork::GDP << std::endl;
cout << "日本的人口与经济总量:" << std::endl;
cout << population << " " << GDP << std::endl; //8
cout << "日本东京的人口与经济总量:" << std::endl;
cout << Tokyo::population << " " << Tokyo::GDP << std::endl; //9
return 0;
}
缺省参数 用法
test.h
int TotalPrice(int NumberOfPeople, int AdmissionFee = 20); // 1
test.cpp
#include <iostream>
#include "test.h"
using namespace std;
int TotalPrice(int NumberOfPeople, int AdmissionFee) // 2
{
return NumberOfPeople * AdmissionFee;
}
int main()
{
char IsStudent = 0;
int NumberOfPeople = 0;
cout << "你是学生吗(Y/N):";
cin >> IsStudent;
if (IsStudent == 'Y')
{
cout << "请输入旅游人数:";
cin >> NumberOfPeople;
cout << TotalPrice(NumberOfPeople, 10);
}
else
{
cout << "请输入旅游人数:";
cin >> NumberOfPeople;
cout << TotalPrice(NumberOfPeople);
}
return 0;
}
函数重载 用法
#include <iostream>
using namespace std;
void Add(int a, int b) // 1
{
cout << a + b << endl;
}
void Add(double a, int b) // 2
{
cout << a + b << endl;
}
void Add(int a, double b) // 3
{
cout << a + b << endl;
}
void Add(double a, double b)
{
cout << a + b << endl;
}
void Add(int a, int b, int c) // 4
{
cout << a + b + c << endl;
}
int main()
{
Add(1, 2);
Add(1.1, 2);
Add(2, 3.3);
Add(1.1, 3.5);
Add(1, 2, 3);
return 0;
}
引用 用法
#include <iostream>
using namespace std;
void Swap(int& a, int& b) // 1
{
int tmp = a;
a = b;
b = tmp;
}
void Print(const double& a, const double& b) // 2
{
cout << a << " " << b << endl;
}
int main()
{
int x = 10;
int y = 20;
Swap(x, y);
cout << x << " " << y << endl;
int m = 100;
int n = 200;
Print(m, n);
return 0;
}
内联函数
#include <iostream>
using namespace std;
inline void add(int& a) // 1 2(声明与定义不能分开)
{
a++;
}
int main()
{
int x = 0;
for (int i = 0; i < 100000000; i++)
{
add(x);
}
cout << x << endl;
return 0;
}