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
相关推荐
everyStudy16 分钟前
JS中判断字符串中是否包含指定字符
开发语言·前端·javascript
luthane18 分钟前
python 实现average mean平均数算法
开发语言·python·算法
Ylucius25 分钟前
动态语言? 静态语言? ------区别何在?java,js,c,c++,python分给是静态or动态语言?
java·c语言·javascript·c++·python·学习
凡人的AI工具箱37 分钟前
AI教你学Python 第11天 : 局部变量与全局变量
开发语言·人工智能·后端·python
sleP4o41 分钟前
Python操作MySQL
开发语言·python·mysql
是店小二呀44 分钟前
【C++】C++ STL探索:Priority Queue与仿函数的深入解析
开发语言·c++·后端
洛寒瑜1 小时前
【读书笔记-《30天自制操作系统》-23】Day24
开发语言·汇编·笔记·操作系统·应用程序
ephemerals__1 小时前
【c++】动态内存管理
开发语言·c++
咩咩觉主1 小时前
en造数据结构与算法C# 群组行为优化 和 头鸟控制
开发语言·c#
CVer儿1 小时前
条件编译代码记录
开发语言·c++