Menu
CoddyTech

참조와 변경

Coddy의 C 개발자를 위한 C++ 코스 레슨. 48개 중 18번째.

C에서는 포인터와 명시적인 역참조를 사용해 쓸 수 있는 별칭을 표현합니다. C++ 참조는 기존 객체에 바인딩되며 일반적인 구문을 사용합니다. 참조 매개변수는 호출한 쪽의 값을 변경할 수 있고, const 참조 매개변수는 복사하거나 변경하지 않고 읽을 수 있게 합니다.

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int main(void){
int n=4;int* alias=&n;*alias+=3;printf("%d\n",n);
return 0;
}

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>

int main(){
int n=4;int& alias=n;alias+=3;std::cout<<n<<"\n";
}

각 프로그램을 독립적으로 추적하세요. 이 예시는 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 일치한다고 가정하지 마세요.

challenge icon

챌린지

쉬움

입력: 두 개의 정수. 참조 매개변수를 통해 두 값의 위치를 바꾸세요. 드라이버는 변경된 호출자 변수를 출력합니다.

exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 수정할 수 있으며, 공개 시그니처를 유지하세요. 잠긴 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 명시된 경우 공개 API 동작도 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 부호 있는 int 범위에 들어갑니다. 별도로 명시되지 않은 텍스트는 ASCII입니다.

직접 해보기

#include "exercise.hpp"
#include <iostream>
int main(){

std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;exchange(a,b);std::cout<<a<<" "<<b<<"\n";
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C 개발자를 위한 C++의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러