저는 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
내 질문 : 왜하지를 "2", "3"및 "4"의 변화는 "하나"에 변화를 가져 오는가?
"two"와 "three"는 어떻게 될지 추측 할 수 있습니다. 아마도 회원이 새로 만든 변수를 복사하는 것이지만 "four"의 변경 사항이 "one"에 반영되지 않은 이유는 모르겠습니다. "(및"5 ") : 결국 GetRef 함수에서 참조를 반환합니다 ....
미리 감사드립니다!
GetRef는 같은 것을 반환하지만 'four'에 할당하면 어떻게됩니까? 그것은 ref가 아닙니다 ... –