我正在学习 C++,特别是,我已经停止阅读引用资料。如果我的问题对你们大多数人来说微不足道,我深表歉意,但我想了解这个程序的输出:
#include <iostream>
using namespace std;
struct myStruct
{
int a;
int b;
};
typedef struct myStruct myStruct;
myStruct copyMyStruct(myStruct& source)
{
myStruct dest;
dest.a=source.a;
dest.b=source.b;
return dest;
}
myStruct otherCopyMyStruct(myStruct& source)
{
myStruct dest;
dest=source;
return dest;
}
myStruct& GetRef(myStruct& source)
{
return source;
}
void printMyStruct(string name,const myStruct& str)
{
cout<<name<<".a:"<<str.a<<endl;
cout<<name<<".b:"<<str.b<<endl;
}
myStruct one,two,three,four;
myStruct& five=one;
void printStructs()
{
printMyStruct("one",one);
printMyStruct("two",two);
printMyStruct("three",three);
printMyStruct("four",four);
printMyStruct("five",five);
}
int main()
{
one.a=100;
one.b=200;
two=copyMyStruct(one);
three=otherCopyMyStruct(one);
four=GetRef(one);
printStructs();
cout<<endl<<"NOW MODIFYING one"<<endl;
one.a=12345;
one.b=67890;
printStructs();
cout<<endl<<"NOW MODIFYING two"<<endl;
two.a=2222;
two.b=2222;
printStructs();
cout<<endl<<"NOW MODIFYING three"<<endl;
three.a=3333;
three.b=3333;
printStructs();
cout<<endl<<"NOW MODIFYING four"<<endl;
four.a=4444;
four.b=4444;
printStructs();
cout<<endl<<"NOW MODIFYING five"<<endl;
five.a=5555;
five.b=5555;
printStructs();
return 0;
}
输出是:
one.a:100
one.b:200
two.a:100
two.b:200
three.a:100
three.b:200
four.a:100
four.b:200
five.a:100
five.b:200
NOW MODIFYING one
one.a:12345
one.b:67890
two.a:100
two.b:200
three.a:100
three.b:200
four.a:100
four.b:200
five.a:12345
five.b:67890
NOW MODIFYING two
one.a:12345
one.b:67890
two.a:2222
two.b:2222
three.a:100
three.b:200
four.a:100
four.b:200
five.a:12345
five.b:67890
NOW MODIFYING three
one.a:12345
one.b:67890
two.a:2222
two.b:2222
three.a:3333
three.b:3333
four.a:100
four.b:200
five.a:12345
five.b:67890
NOW MODIFYING four
one.a:12345
one.b:67890
two.a:2222
two.b:2222
three.a:3333
three.b:3333
four.a:4444
four.b:4444
five.a:12345
five.b:67890
NOW MODIFYING five
one.a:5555
one.b:5555
two.a:2222
two.b:2222
three.a:3333
three.b:3333
four.a:4444
four.b:4444
five.a:5555
five.b:5555
我的问题:为什么“二”、“三”和“四”的变化不会对“一”产生变化?
我能猜到“二”和“三”发生了什么:可能一个成员一个成员复制到一个新创建的变量,但我不明白为什么“四”的变化没有反射(reflect)在“一”上(和“五”):毕竟我从 GetRef 函数返回了一个引用....
提前致谢!
最佳答案
变量 four
是一个对象,而不是一个引用。
当您从引用对其赋值时,four=GetRef(one);
,four
不会变成引用。赋值复制引用引用的任何内容(在本例中,引用对象是 one
)。在那之后,对象是无关的。所以 four = GetRef(one);
与 four = one;
具有相同的效果。
myStruct &five = one;
另一方面,将 five
声明为引用(不是对象),并“绑定(bind)”对象 one
引用。所以名称 five
和名称 one
指的是同一个对象,这意味着当然可以使用另一个名称看到使用其中一个名称所做的更改。
顺便说一下,在 C++ 中不需要 [*] typedef struct myStruct myStruct;
。在 C++ 中,类类型只能通过名称来引用,而结构是类。
[*] 除了一个有点奇怪的角落情况,你有一个与类同名的函数,其参数与该类的某些构造函数的参数兼容。那么您可能会认为表达式 Foo(x,y)
在函数 Foo
和对 Foo
的构造函数调用之间会产生歧义。但不是——在没有 typedef 的情况下,C 当然会选择函数,因此为了与 C 兼容,C++ 做同样的事情。大多数人认为这种情况不足以用 C++ 编写 typedef。
关于c++ - 关于引用传递的疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4230678/