【C++入门】 初见,单推,与C++的第一次约会
引言:本篇博客我们开始与C++的第一次约会,C++是兼容c的,本篇博客我们将了解到C++关键字有哪些,C++命名空间,C++输入与输出和缺省参数的内容,请放心食用 ~
文章目录
- 一 🏠 C++关键字
- 二 🏠 C++命名空间
- 👿 命名空间的定义
- 👿 命名空间的使用
- 📒 加命名空间名称及作用域限定符
- 📒 展开命名空间
- 📒 指定展开空间的某一个
- 三 🏠 C++输入与输出
- 👿 cout和cin
- 关于std命名空间
- 四 🏠 缺省参数
- 👿 缺省参数的概念
- 👿 缺省参数的分类
一 🏠 C++关键字
C++跟C语言一样也有属于它自己关键字,但是由于C++兼容c,关键字中有些是我们的老朋友,有些是新朋友,我们可以在后期慢慢了解
二 🏠 C++命名空间
我们首先看这样的一段代码
#include #include int rand = 0; int main() { printf("%d",rand); return 0; }这段代码能否正常输出这个全局变量rand的值呢?
答案是否定的,这是因为我们包含了rand函数的头文件,他和rand变量都在全局域中,这导致编译器懵逼了会起冲突。
这里我们补充一个知识点:我们在用变量/函数..时,编译器默认查找顺序是1.局部域 2.全局域
那有什么解决之法呢 ? C++ 给了一个新技术叫做 命名空间(namespace)
👿 命名空间的定义
- 语法
namespace 空间名 { int rand = 10; // 定义变量 int Add(int x,int y) { return x + y; } //定义函数 struct Node { }; //定义类型 } //注意这里没有分号 ! !命名空间里可以定义变量,函数,类型
// test.cpp namespace N1 { int a; int b; int Add(int left, int right) { return left + right; } namespace N2 { int c; int d; int Sub(int left, int right) { return left - right; } } }命名空间也可以嵌套命名空间,有什么使用场景呢?
namespace bit { namespace f { void Add(int x, int y) { cout int x; void Add(int x, int y) { cout }; } int main() { bit::f::Add(1, 2); f::Add(1, 2); return 0; } void Sub(int x ,int y) { cout int x; void Add(int x, int y) { cout }; } #include"test.h" int main() { bit::f::Add(1, 2); f::Add(1, 2); f::Sub(1, 2); return 0; } int x = 2;; void Add(int x, int y) { cout }; } int x = 0; int main() { cout printf("%d\n", N::a); printf("%d\n", b); Add(10, 20); return 0; } int val = 0; } namespace f2 { int val = 1; } using namespace f1; using namespace f2; cout int b = 0; } using N::b; int main() { printf("%d\n", b); return 0; } int rand = 0; } using N::rand; int main() { printf("%d\n", b); return 0; } cout Func(); // 没有传参时,使用参数的默认值 Func(10); // 传参时,使用指定的实参 return 0; } cout cout}
- 语法
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!


