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
相关推荐
默 语3 小时前
HarmonyOS7 事件分发控制(二):onTouchIntercept 镂空玻璃卡——圆内自己接,圆外放行
android·java·开发语言
Amumu121384 小时前
TypeScript学习: 基础知识(二)
开发语言·typescript·ecmascript
derek19974 小时前
软考软件设计师:B-树和 B+树的区别、线性探查法查找时到底比较了谁
c语言·c++·计算机网络·软件工程·学习方法
sharemylove4 小时前
Java 异常与常用类 学习笔记
java·开发语言·经验分享·笔记·学习
小灰灰搞电子4 小时前
C 语言基础:动态内存管理详解
c语言·开发语言
打工仔折腾 AI5 小时前
L3 静态源码取证|工程评测:python-oracledb 驱动评估中的样本偏差陷阱
开发语言·人工智能·后端·python·性能优化
fqbqrr5 小时前
2612C++,C++量钢问题
c++
Amumu121385 小时前
TypeScript学习: 进阶知识
开发语言·学习·typescript
充电zcx6 小时前
C++ 复习:stack、queue 与仿函数——容器适配器、priority_queue 与 deque 的取舍
c++·queue·仿函数·stack·priority_queue
Helix2506 小时前
JDK异常处理最佳实践:受检异常、非受检异常、try-catch-finally与全局异常处理完整指南
java·开发语言·jdk·异常处理·全局异常·自定义异常·try-catch