C++核心编程

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

C++第一个程序

cpp 复制代码
/*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

cpp 复制代码
#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

cpp 复制代码
#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也可以自动识别基础的数据类型

名字空间

cpp 复制代码
#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;

无名名字空间

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

cpp 复制代码
#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;
}

名字空间嵌套

cpp 复制代码
#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
相关推荐
saltymilk7 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥8 小时前
C++ lambda 匿名函数
c++
沐怡旸14 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥14 小时前
C++ 内存管理
c++
博笙困了21 小时前
AcWing学习——双指针算法
c++·算法
感哥21 小时前
C++ 指针和引用
c++
感哥1 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥2 天前
C++ std::set
c++