当我以不同方式定义对同一变量的引用时,结果不同
Different results when I define references to same variable in different ways
我定义了这样的类
class A
{
public:
A(int a, int b):a(a),b(b){}
void test(const char* name) {cout<<name<<": "<<a<<" "<<b<<endl;}
public:
int a,b;
};
然后主函数:
int main()
{
A obj(1,2);
A& ref_1=obj;
A& ref_2=obj;
ref_1.a = 2;
ref_1.test("ref_1");
ref_2.test("ref_2");
cout<<&obj<<endl<<&ref_1<<endl<<&ref_2<<endl;
return 0;
}
我期望的结果是
ref_1: 2 2
ref_2: 2 2
0x7fff59bb0c90
0x7fff59bb0c90
0x7fff59bb0c90
但是,当我定义两个参考时:
A& ref_1=obj, ref_2=obj;
结果非常奇怪:
ref_1: 2 2
ref_2: 1 2
0x7fff58a68c90
0x7fff58a68c90
0x7fff58a68c80
我将G 用作编译器。谁能告诉我为什么这件事会发生?
A& ref_1=obj, ref_2=obj;
等于
A& ref_1=obj;
A ref_2=obj;
如果您希望两者都是参考,则需要写
A &ref_1=obj, &ref_2=obj;
另外,完全避免这种混乱,然后写
A& ref_1=obj;
A& ref_2=obj;
就像您最初的一样。
当您以 A& ref_1=obj, ref_2=obj;
的形式编写它时,就好像您以
A& ref_1=obj;
A ref_2=obj;
如果您想在一行上写下它,并且两个是参考文献,则需要将其写为
A &ref_1=obj, &ref_2=obj;
您已经陷入了先例之一。
当您所写的内容读为" ref_1 and ref_2为ref-to-a"时,&
实际上绑定到变量而不是类型。指针也发生了同样的事情。这就是为什么关于哪种更正确的撰写参考/指针的方式进行的持续辩论。
A& ref_1; // ref_1 is a reference to type A.
A &ref_1; // means the same thing.
A& ref_1, ref_2;
A &ref_1, ref_2; // same as above.
A &ref_1, &ref_2; // what you thought the first line mean't
A* p1, p2; // p1 is a pointer, p2 is an instance of A
A *p1, *p2; // what you actually intended on the previous line.
相关文章:
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- c++ lambda:柯里和函数:使用按值捕获与按引用捕获返回不同的结果
- C++ 获取函数在常量引用中按值返回的结果
- 取消引用指向整数的指针时获得不同的结果
- 按值传递变量与按引用传递变量具有相同的结果
- 如果结果存储在变量中forward_as_tuple然后在 std::apply 中使用之前丢失右值引用
- 在我的C++链表实现中取消引用节点指针,给出意想不到的结果
- 传递右值引用结果编译错误unique_ptr
- std::具有自定义比较函数结果的排序函数错误:必须调用对非静态成员函数的引用
- 对 std::atomic::load 的结果使用结构取消引用 (->) 运算符是否安全
- 未给出预期结果的引用
- C++宏中相互引用的奇怪结果
- 强制转换为父类对象而不是引用时会出现哪些不良结果
- 为什么"decltype(i+j)"的结果不是右值引用?
- c++按值传递、按引用传递或按值传递结果
- 简单的代码,看似随机的结果——这是由于过时的引用造成的吗
- 取消引用无效指针但不使用结果是否是C++中的未定义行为
- 取消引用运算符给出的结果与具有 void* 的数组偏移运算符不同
- 在取消引用的函数指针上使用时,std::is_function的求值结果为何为false
- std::is_same具有左值和右值引用的结果