【C++】引用的使用
引用简单应用
#include<iostream>
using namespace std;
int main()
{
int a = 10;
int& b = a;//b引用了a,实际为a的别名,a和b指向同一块内存区域;修改a或者b的值均同时改变对方的值。
b = 20;
cout << a << endl;
cout << b << endl;
}
实际上a和b共同指向一片内存区域,如果尝试引入int& c = b;然后修改c的数值,那么a,b,c将共同执向同一片内存区域。
实际用法:改变外部变量
#include<iostream>
using namespace std;
void increment(int x)
{
x++;
}
int main()
{
int a = 5;
increment(a);
cout << a << endl;
}
假设这样写,实际上打印出来的a仍是5,因为a作为局部变量的数值无法在外部被改变。
#include<iostream>
using namespace std;
void increment(int& x)
{
x++;
}
int main()
{
int a = 5;
increment(a);
cout << a << endl;
}
上图使用引用作为值传递,可以在不使用指针或者返回值的方式对a的值进行修改,并且节省了内存的开销。
=========================================================================
链式调用
#include <iostream>
using namespace std;
class Builder {
public:
Builder& setA(int value) {
a = value;
return *this;
}
Builder& setB(int value) {
b = value;
return *this;
}
void print() const {
cout << "a = " << a << ", b = " << b << endl;
}
private:
int a = 0, b = 0; // 初始化 a 和 b 为 0
};
int main() {
Builder builder;
builder.setA(10).setB(20); // 链式调用
builder.print();
return 0;
}
原文地址:https://blog.csdn.net/weixin_41598714/article/details/142820860
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!