指针也能达到这种效果
发布时间:2025-06-24 04:56:57 作者:北方职教升学中心 阅读量:008
指针也能达到这种效果。
struct hx::Node node;
,访问结构体。对 b * 2
的结果会存放在一个临时变量中,将b * 2的结果计算出来后,编译器放在一个临时对象中,存储中间值。
#include <iostream>using namespace std;int Add(int a, int b, int c = 3){ return a + b + c;}int main(){ cout << Add(10, 20, 30) << endl; return 0;}
例如,在对栈的数据结构进行初始化时,可以给一个缺省值,我可以不传递参数让其默认开辟4个空间。const修饰的对象。
int main(){ const int a = 0; //编译器报错 error C2440: “初始化”: 无法从“const int”转换为“int &” //int& ra = a;//权限放大 const int& ra = a;//平等关系 int b = 0; int& rc = b; const int& rd = b;//权限缩小 //error C3892: “rd”: 不能给常量赋值 //rd++; rc++; return 0;}
类似于对 int& rb = b * 2; float& d = 3.14; int& rd = d;
。调用函数返回后,它的返回值存放在一块临时对象中它具有常性无法被修改。
引用就是取别名,引用不是新定义一个变量,而是给以存在变量取一个别名,编译器不会为引用变量开辟内存空间,它和引用的变量共同使用同一块内存空间。b、
void test(){ cout << "void test()" << endl;}void test(int n = 4){ cout << "void test(int n = 4)" << endl;}int main(){ test(); return 0;}
引用(reference)
引用概念
很牛的东西。
#include <iostream>namespace hx{ int rand = 6; int Add(int left, int right) { return left + right; } struct Node { int val; struct Node* next; };}
namespace本质上是定义了一个域,这个域跟全局域各自独立,不同域可以定义同名变量。
- 由于这些机制导致了cout的效率不会很高
这三句代码可以提高,C++IO流的效率
int main(){ ios_base::sync_with_stdio(false);//使C语言和C++不同步兼容 cin.tie(nullptr); cout.tie(nullptr);//将cin和cout相互绑定的关系,不会与其它流相互关联 return 0;}
缺省参数
C++中的缺省参数(默认参数),允许在对函数进行声明或定义时为函数参数提供一个缺省值。
所谓临时对象就是编译器需要⼀个空间暂存表达式的求值结果时临时创建的⼀个未命名的对象, C++中把这个未命名对象叫做临时对象。
- namespace关键字后面跟上命名空间的名字,通过大花括号( {} )括在一起,{}中为名称空间的成员,在名称空间内可以对,变量、
- 全缺省参数,给全部形参缺省值,C++规定必须从左到右依次给实参,不能跳跃给实参
#include <iostream>using namespace std;int Add(int a = 1, int b = 2, int c = 3){ return a + b + c;}int main(){ cout << Add() << endl; cout << Add(10) << endl; cout << Add(10, 20) << endl; cout << Add(10, 20, 30) << endl; return 0;}
全缺省参数的,几种调用形式
Add()
,没有传递参数,调用函数add是使用三个缺省值。- 使用nullptr就可以避免上述情况出现的问题
- namespace关键字后面跟上命名空间的名字,通过大花括号( {} )括在一起,{}中为名称空间的成员,在名称空间内可以对,变量、