gpt4 book ai didi

c++ - 引用类型示例问题

转载 作者:行者123 更新时间:2023-11-27 23:54:04 25 4
gpt4 key购买 nike

假设我有以下 C++ 示例程序:

#include <iostream>
using namespace std;

int main (int argc , char** argv) {

int a = 1;
int b = 2;
int& aRef = a;
int& bRef = b;
aRef = bRef; // This just sets aRef to point to b?
aRef = 3; // Now aRef points to a new int 3 not stored in a other variable?
// a = 3 b = 2
bRef = 4;
// a = 3 b = 4
aRef = long(&bRef); // Why do we need long casting here?
bRef = 5;
// a: varying b = 5 // Why is a varying?
aRef = bRef;
bRef = 6;
// a = 5 b = 6 // Why a no more varying?

}

有人可以逐行解释并揭示错误吗?我在我特别不清楚的行中添加了注释。

最佳答案

#include <iostream>
using namespace std;

int main (int argc , char** argv) {
int a = 1;
int b = 2;
int& aRef = a; // aRef is now another name for a
int& bRef = b; // bRef is now another name for b
aRef = bRef; // same as a = b
aRef = 3; // same as a = 3
bRef = 4; // same as b = 4
aRef = long(&bRef); // &bRef is the same as &b - i.e. take address of b - stores address in a
bRef = 5; // same as b = 5
aRef = bRef; // same as a = b
bRef = 6; // same as b = 6

}

关于c++ - 引用类型示例问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43946380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com