C++核心编程

C++涉及以下领域开发:

C++第一个程序

/*iostream:C++使用IO相关函数的头文件,类似与stdio.h;
C++风格的头文件没有.h后缀
C++兼容C,C++也可以使用stdio.h 
也提供C++风格的头文件,如cstdio,该头文件一般存在于/usr/include/c++/4.8/
*/
#inclucd <iostream>//名字空间
using namespace std;int main(void) {/*类似于printf("hello world!\n");count:输出对象<<:输出插入运算符endl:换行符*/cout << "hello world!" <<endl;return 0;
}
/*
首先创建.cpp文件
编译:两种方式 一种为gcc helloword.cpp -o hello -lstdc++一种为g++ helloword.cpp -o hello
两种方式均可以编译*/

COUT

#include <iostream>using namespace std;int main(void) {int a = 10;flost b = 2.2;char c = 'z';cout << a << " " << b << " " << c <<endl;
}//输出结果为10,2.2,z; cout可以自动识别基础的数据类型;

cin

#include <iostream>using namespace std;int main(void) {int a;float b;char c;cin >> a >> b >> c;cout<< a << b << c <<endl;
}//当屏幕输入11.12a时,输出结果为11 0.12 a;cin也可以自动识别基础的数据类型

名字空间

#include <iostream>using namespace std;namespace fuc1{void func(void) {cout << "fuc1" << endl;}
}namespace fuc2 {void func(void) {cout << "fuc2" << endl;}
}int main() {using fuc1::func;fuc1::func();fuc2::func();func();func();func();return 0;
}

注释:当定义相同的名字的时候,使用名字空间包装,可以避免报错;

调用名字空间的方法有三种

1、使用作用于限定符(::)可以引用名字空间单个成员;前面为名字空间名称,中间两个冒号,后面为调用函数

2、使用using fuc1::func;之后,后面再调用func均为名字空间fuc1里面的;这个方法适合大量使用fuc1的内容时使用;

3、当名字空间有很多个内容是,使用using namespace fuc1; 

无名名字空间

未命名的名字空间称为无名名字空间;

#include <iostream>using namespace std;namespace fuc1{void func(void) {cout << "fuc1" << endl;}int a = 100;
}namespace fuc2 {void func(void) {cout << "fuc2" << endl;}int a = 200;
}namespace {int a = 300;
}int main() {int b;fuc1::func();fuc2::func();cout<< fuc1::a << " " << fuc2::a << " " << ::a <<endl;return 0;
}

名字空间嵌套

#include <iostream>using namespace std;namespace ns1{void func(void) {cout << "this is ns1" <<endl;}namespace ns2{void func(void) {cout << "this is ns2" << endl;}}
}int main() {ns1::ns2::func();
}
//输出结果为:this is ns2