[C#] 연산자 오버로딩 , 프로퍼티 예제 본문

[PL]/C# & WPF

[C#] 연산자 오버로딩 , 프로퍼티 예제

객과 함께. 2011. 6. 16. 22:44

(1)연산자 오버로딩 함수이용 , 프로퍼티 예제

/*
* 프로퍼티 , 오버로딩 그리고 오버로드
*/
namespace 연산자오버로딩예제
{
class Program
{
static private string str1; //콘솔에서 입력한 원문의 데이터
static private int str2; // 삭제할 위치값을 입력 받는다.


/// <summary>
/// 프로퍼티 -클래스는 액세스 지정자라는 것을 통해 중요한 멤버를 외부로 부터 보호 할 수 있다.
/// 주요 필드는 모두 private액세스 지정자 를 붙여 외부에서 값을 함부로 읽거나 쓰지 못하도록 하고 대신
/// 공개된 Get/Set메서드를 제공한다.
/// Get - 값을 리턴 할때 사용
/// Set - 외부에서 들어온 값을 저장 할 때 사용
///
/// params를 받을 인자변수가 없다.
/// </summary>
static public string strValue //메인 메서드가 static으로 선언되어
{ //있기 때문에 프로퍼티 역시 static으로 선언 하였다.
get { return str1; }
set { str1 = value; }
}

static public int intValue
{
get { return str2; }
set { str2 = value; }
}

static void Main(string[] args)
{

Console.WriteLine("연산자 오버로딩");
Console.Write("문자열 입력 : ");
strValue = Console.ReadLine();

Console.Write("삭제 할 인덱스 입력 : ");
intValue = int.Parse(Console.ReadLine()); //int.parse()는 문자열주에 숫자로 변환가능한 것을 정수형으로
// 컨버터시킴.

/*
* Operator stVal = new Operator(strValue); Operator클래스의 strVal값을 넘겨주기 위해서 힘에 올라온
* 영역에 접근을 하기 위해서 new를 사용해서 클래스에 접근하였다.
* Console.WriteLine("{0}", stVal - intValue); stVal - intValue 연사자를 오버로딩 호출을 위한 부분.
*
* 연산자 오버로딩 - 원래부터 존재 하는 연산자 함수를 클래스 타입에 대해 중복 정의하여 객체에 대한 고유한 연산을 정의
* 하는것.
*
* = -> 기본적인 연산자라 오버로딩 할 수 없다.
* [] -> 연산자는 인덱서로 대신 정의 할 수 있으므로 오버로딩 할 수 없다.
* &&, || -> 오버로딩이 할 수 없다.
*/
Operator stVal = new Operator(strValue);
Console.WriteLine("{0}", stVal - intValue);
}
}

class Operator
{
private string strVal;
private int intVal;

public Operator(string astrVal) //생성자 오버로드
{
strVal = astrVal;
}

public Operator(int inVal) //생성자 오버로드
{
intVal = inVal;
}


public static string operator -(Operator strVal, int intVal) //연산자 오버로딩 메서드
{
string result , result1;

int a = strVal.strVal.Length;
if (a > intVal && 0 < intVal) //strVal 의 입력에 길이보다 크거나 0보다 작은 것을 비교 연산한다.
{
result = strVal.strVal.Substring(0, intVal); //추출함수인 Substring()를 이용해 해당 하는 문자열 만큼 추출 한다.
result1 = strVal.strVal.Substring(intVal + 1);
result += result1;

}
else
{
result ="범위가 벗어났습니다. ";
}
return result; //연산된 결과를 리턴.

}

}

(2)연산자 오버로딩 함수이용 예제

// Operator 클래스

class Operator
{
string strResult;
int intValue;

public Operator(string str)
{
this.strResult = str;
}

public Operator(int val)
{
this.intValue = val;
}

public static string operator -(Operator a1, int a2)
{
string result = "", result1= "", result2 = "";
result1 = a1.strResult.Substring(0, a2 );
result2 = a1.strResult.Substring(a2 + 1) ;
result = string.Concat(result1, result2); //msdn에서 찾은 함수 입니다. result1 과 result2를 서로연결

// 시켜주는 함수라고 합니다.
return result;

}
}

'[PL] > C# & WPF' 카테고리의 다른 글

[c#.net] Request 객체와 Response객체   (0) 2011.07.19
[C#] 인덱스 , 상속 정리   (0) 2011.06.16
참조 , 값   (0) 2011.06.08
[교육원] 변수 ,구조체 및 배열 정리  (0) 2011.06.08
[교육원]기본문법  (0) 2011.06.01