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
相关推荐
EutoCool5 分钟前
Qt窗口:菜单栏
开发语言·c++·嵌入式硬件·qt·前端框架
nightunderblackcat39 分钟前
新手向:使用Python将多种图像格式统一转换为JPG
开发语言·python
我爱Jack1 小时前
深入解析 LinkedList
java·开发语言
engchina1 小时前
Python PDF处理库深度对比:PyMuPDF、pypdfium2、pdfplumber、pdfminer的关系与区别
开发语言·python·pdf
拓端研究室1 小时前
专题:2025供应链数智化与效率提升报告|附100+份报告PDF、原数据表汇总下载
开发语言·php
一百天成为python专家1 小时前
python库之jieba 库
开发语言·人工智能·python·深度学习·机器学习·pycharm·python3.11
Go Dgg2 小时前
【Go + Gin 实现「双 Token」管理员登录】
开发语言·golang·gin
圆头猫爹2 小时前
第34次CCF-CSP认证第4题,货物调度
c++·算法·动态规划
十五年专注C++开发2 小时前
hiredis: 一个轻量级、高性能的 C 语言 Redis 客户端库
开发语言·数据库·c++·redis·缓存
WJ.Polar2 小时前
Python数据容器-集合set
开发语言·python