c++拾遗录

来源:互联网 发布:国外域名后缀 编辑:程序博客网 时间:2024/06/14 00:08
命名空间意义防止变量重名冲突#include"main.h"#include<iostream>using namespace std;int num = 10;void main(){ cout << num << endl;cout << data::num << endl;//::域作用符cin.get();}命名空间权限#include<iostream>#include<cstdlib>using namespace std;namespace  string1{char str[10]={ "calc" };}namespace  string2{char str[10]={ "notepad" };}//命名空间拓展,名称相同,同一个命名空间//瀑布式开发namespace  string2{char cmd[10]={ "notepad" };void show(){cout << str << endl;}}//命名空间,可以无限嵌套namespace run{namespace runit{namespace runitout{int num = 100;void show(){cout << num << endl;}}}}void main(){//system(string2::str);//string2::show();//命名空间的函数与变量run::runit::runitout::num = 199;run::runit::runitout::show();system("pause");}匿名命名空间#include<iostream>using namespace std;//匿名命名空间等同全局变量namespace{int x = 10;}void main(){x = 3;cout << x << endl;cin.get();}using#include<iostream>namespace run1{int x = 10;}namespace run2{int x = 10;void show(){std::cout << x << std::endl;}}void run(){using namespace std;//等同局部变量using namespace run1;using namespace run2;//发生//cout << "hello world"<<x;}void main(){std::cout << "hello doubo";using  run2::x;using  run2::show;//单独引用命名空间变量或者函数std::cout << x << std::endl;show();std::cin.get();}命名空间深入#include<iostream>//using,可以省略std,//制定命名空间,//原则禁止using namespace std;//明确空间namespace  stdrun{int num = 101;void show(){std::cout << num << std::endl;}}namespace bobo = stdrun;//给自定义的别名namespace doubo = std;//给标准别名,不推荐//有些CPP编译器设置,禁止改变标准void main(){bobo::show();doubo::cout << "hello";doubo::cin.get();}模板#include<iostream>#include<cstdlib>using namespace std;//add CPP 函数重载,//函数模板意义,通用,泛型//调用的时候编译,不调用不编译//原生函数优先于模板函数,强项调用模板add<int>(1, 2)int add(int a, int b){cout << "int" << endl;return a + b;}//char add(char  a, char b)//{//return a + b;//}//double add(double a, double b)//{//return a + b;//}//调用的时候编译,不调用的时候不编译template<class T>T add(T a, T b){cout << "T" << endl;return a + b;}void main1(){//cout << add(1, 2) << endl;//3,原生函数优先于模板函数//cout << add<int>(1, 2) << endl;//3,原生函数优先于模板函数//cout << add('1', '2') << endl;system("pause");}模板接口#include<iostream>using namespace std;void show(int num){cout << num << endl;}void show1(double num){cout << num+1 << endl;}template<class T>void showit(T num){cout << num << endl;}//泛型接口,任何数据类型,传递函数指针template<class T ,class F>void run(T t,F f){f(t);}void main(){run(10.1, show1);//run("abc", showit);error没有与参数列表匹配的 函数模板 "run" 实例参数类型为: (const char [4], <unknown-type>)//在模板接口中若函数也使用模板,则必须指定参数类型run("abc",showit<const char*>);//接口,严格类型,cin.get();}

                                             
0 0
原创粉丝点击