값 및 참조 의미론
Coddy의 C++ 개발자를 위한 C# 코스 레슨. 48개 중 30번째.
C++ 클래스 객체는 참조나 포인터를 통해 접근하지 않는 한 값 복사 의미를 가집니다. C# 구조체는 값을 복사하지만 C# 클래스 변수는 참조를 복사합니다. C++의 class 키워드가 C#의 class 키워드와 같은 대입 동작을 의미하는 것은 아닙니다.
구조체 대입은 값을 복사하고, 클래스 대입은 객체에 대한 참조를 복사합니다. 복사한 구조체 필드를 변경해도 원본은 바뀌지 않지만, 별칭이 지정된 클래스를 변경하면 원본도 바뀝니다. 구조체에는 여전히 참조가 포함될 수 있으므로, 값 복사가 항상 완전한 깊은 복제인 것은 아닙니다.
C++ 참조
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
struct Point { int x; };
int main() {
Point a{2};
Point b=a; b.x=9;
cout << a.x << "\n";
}
C# 보조 선언
struct Point { public int X; public Point(int x) { X = x; } }Main 내부의 C# 문장
Point a = new Point(2);
Point b = a; b.X = 9;
Console.WriteLine(a.X);이 내용은 핵심을 설명하기 위한 발췌문입니다. 과제 파일에는 실행 가능한 전체 래퍼 코드가 포함되어 있으며, 위 코드 조각은 관련 선언과 문장만 보여 줍니다.
참조 출력:
2C# 출력:
2챌린지
쉬움제공된 Point 구조체와 Box 클래스를 사용하세요. point를 복사하고 복사본만 change만큼 변경하세요. box 별칭을 할당하고 같은 양만큼 변경하세요. originalPoint,changedPoint,originalBox를 쉼표로 구분된 정수로 반환하세요.
잠금 해제된 C# 파일을 수정하세요. 잠겨 있는 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하고, 입력이 변경되지 않았는지 확인한 다음 마지막에 줄 바꿈을 하나 붙여 결과를 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 하지 마세요.
직접 해보기
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
C++ 개발자를 위한 C#의 모든 레슨
1여기서 시작하기
첫 C# 프로그램 실행하기직접 연습해 보세요: 온라인 C# 컴파일러