我正在學習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
我的問題:爲什麼不「二」,「三」和「四」的變化會對「一」產生變化嗎?
我可以猜到「two」和「three」會發生什麼:可能是成員通過成員複製到新創建的變量,但我不明白爲什麼「four」上的更改沒有反映在「one 「(和」五「):畢竟我從GetRef函數返回一個參考....
在此先感謝!
GetRef返回相同的內容,但當分配給'four'時會發生什麼?這不是一個參考... – 2010-11-20 01:11:46