내부 클래스 용도

|
http://thdwns2.springnote.com/pages/539147

1. 인스턴스 내부 클래스
Ex0608.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Outer {
	int outData = 100;
	class Inner {
		public void printInner() {
			System.out.println(outData);
		}
	}
}

public class Ex0608 {
	public static void main(String args[]) {
		Outer out = new Outer();
		Outer.Inner in = out.new Inner();
		in.printInner();
	}
}

2. static 내부 클래스
원래 클래스 앞에는 static이 붙을 수 없다. 하지만 내부 클래스일 경우는 데이터 타입처럼 사용되기 때문에 가능한데 의미는 Outer 클래스의 인스턴스가 없어도 생성 가능한 내부 클래스라는 것이다. static이므로 이미 Outer 클래스 생성시에 정의되어 있는 상태이다. 
Ex0609.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Outer {
	static int outStaticData = 100;
	static class Inner {
		public void printInner() {
			System.out.println(outStaticData);
		}
	}
}

public class Ex0609 {
	public static void main(String args[]) {
		Outer.Inner in = new Outer.Inner();
		in.printInner();
	}
}

3. 지역 클래스
Ex0610.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Outer {
	int outData = 100;
	Object outerMethod() {
		final int localFinalData = 200;
		class Inner extends Object {
			public String toString() {
				return "내부 클래스의 메소드 : " + outData + 
				", " + localFinalData;
			}
		}
		return new Inner();
	}
}
public class Ex0610 {
	public static void main(String args[]) {
		Outer out = new Outer();
		Object obj = out.outerMethod();
		System.out.println(obj.toString());
	}
}

4. 내부 무명 클래스
Ex0611.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Outer {
	int outData = 100;
	
	Object outerMethod() {
		final int localfinalData = 200;
		
		return (new Object() {
			public String toString() {
				return "내부 클래스의 메소드 : " + outData + 
				" " + localfinalData;
			}
		});
	}
}
public class Ex0611 {
	public static void main(String[] args) {
		Outer out = new Outer();
		Object obj = out.outerMethod();
		System.out.println(obj.toString());
	}
}

'Java' 카테고리의 다른 글

Exception  (0) 2010.08.23
자바 주요 클래스  (0) 2010.08.19
static vs final  (0) 2010.08.17
주민등록번호 추출  (0) 2010.08.16
자바 소수점 출력  (0) 2010.08.13
And

[ImageView]

|
1. ImageView.java 생성
2. View 클래스를 상속받은 클래스는 생성자가 반드시 있어야 하므로 ImageView(Context context) {...} 생성
3. 콘텍스트에서 리소스를 가져온다.
4. 가져온 리소스를 디코드한다.
5. onDraw()를 오버라이드하여 drawBitmap()으로 그림을 그린다.


ImageTest.java
C++pasted just now: 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package net.itisn.test;

import android.app.Activity;
import android.os.Bundle;

public class ImageTest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        setContentView(new ImageView(this));
    }
}

ImageView.java
package net.itisn.test;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;

public class ImageView extends android.widget.ImageView {

	private Bitmap image;
	public ImageView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.setBackgroundColor(Color.WHITE);
		
		//그림 읽기
		Resources r = context.getResources();
		image = BitmapFactory.decodeResource(r, R.drawable.icon);
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		canvas.drawBitmap(image, 0, 0, null);
		
		int w = image.getWidth();
		int h = image.getHeight();
		Rect src = new Rect(0, 0, w, h);
		Rect dst = new Rect(0, 70, w*3, h*3+70);
		canvas.drawBitmap(image, src, dst, null);
	}
}



-end

'Android' 카테고리의 다른 글

[AlertDialog]  (0) 2010.08.18
[MenuTest]  (0) 2010.08.18
[LifeCycle]  (0) 2010.08.17
[ShapeEx]  (0) 2010.08.16
[.java로 View Control]  (0) 2010.08.16
And

[LifeCycle]

|
인텐트 : 액티비티간 메시지 전달시 사용? 일종의 객체 직렬화??

TestLifeCycle.this.startActivity(intent);
객체를 생성하지 않았으므로 자신을 가리키기 위해서는 TestLifeCycle.this를 써야 한다.

Log는 Trace에서 사용
EJB에서도 Log 사용

소스코드가 바뀌면 일일이 수정 필요

스프링 프레임워크에서는 관점지향 프로그래밍을 사용 Aspect-Oriented Programming
Aspect-O...용 컴파일러도 있음 AspectJ
컴파일하면서 로그를 삽입해줌...CrossCut

Log filter

우측 상단 창+모양 클릭 > 디버그
로그캣 > + 클릭 > Name : TestLifeCycle, Tag : TestLIfeCycle 입력 > 디버그

1. 버튼을 가져온다.
2. 버튼에 클릭이벤트를 생성한다.
3. 클릭이벤트 메소드를 정의한다. 액션뷰 인텐트를 생성한다.
4. 오버라이딩한 메소드마다 로그를 남긴다.

Intent란?

LifeCycleTest.java
package net.itisn.test;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TestLifeCycle extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Button button = (Button)this.findViewById(R.id.Button01);
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				// TODO auto-generated method stub
				Intent intent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("http://www.google.com"));
				TestLifeCycle.this.startActivity(intent);
			}
		});
		Log.i("TestLifeCycle", "onCreate");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i("TestLifeCycle", "onDestroy");
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.i("TestLifeCycle", "onPause");
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		Log.i("TestLifeCycle", "onRestart");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i("TestLifeCycle", "onResume");
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Log.i("TestLifeCycle", "onStart");
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.i("TestLifeCycle", "onStop");
	}
}


-end


'Android' 카테고리의 다른 글

[MenuTest]  (0) 2010.08.18
[ImageView]  (0) 2010.08.17
[ShapeEx]  (0) 2010.08.16
[.java로 View Control]  (0) 2010.08.16
[RelativeLayout] 0. 레이아웃 만들기  (0) 2010.08.13
And

다중 상속의 문제점

|
#다중 상속의 문제점
1. 상속받은 두 클래스에 같은 이름의 함수가 있을 경우, 어느 함수를 호출해야 할 지 알 수 없다.

>>어느 클래스의 함수인지 명시한다.
>>객체.부모클래스::멤버함수();

2. B가 A를 상속받고, C도 A를 상속 받은 후, D가 B와 C를 상속 받는 경우, A가 두 번 포함된다. (다이아몬드 상속)

>>B와 C가 A를 virtual 상속받는다.
>>class B : virtual public A {...}
>>class C : virtual public A {...}
>>class D : public B, public C {...}
D에서 A의 멤버 함수를 사용하려면 B::멤버 함수 또는 C::멤버 함수로 사용하여야 한다.
A::멤버 함수로는 사용할 수 없다. B와 C가 virtual로 A를 상속받았기 때문이다.

'C++' 카테고리의 다른 글

C++ 생성자  (0) 2010.08.13
생성자와 소멸자  (0) 2010.08.13
c++ 오버라이딩  (0) 2010.07.03
동적 할당 0614  (0) 2010.06.14
c++ 0610  (0) 2010.06.10
And

주민등록번호 추출

|

RRNTest.java
by Parsing
class RRN {
	String[] validNum = new String[30];
	public void ValidateNumbers(String str) {
		//System.out.println(str.length());
		int i = 0, j = 0, k = 0;
		while (i < str.length()-12) {
			for (j = 0; j < 13; ++j) {
				if (!(str.charAt(i+j) >= '0' && str.charAt(i+j) <= '9')) {
					break;
				}
				else if (j == 12) {
					validNum[k] = str.substring(i, i+13);
					k++;
				}
			}
			++i;
		}
	}
	
	public void Validate() {
		for (int i = 0; i < validNum.length; ++i) {
			if (validNum[i] != null && validNum[i] != "Invalid") {
				System.out.println(ValidateYY(validNum[i]));
			}
		}
	}
	
	public String ValidateYY(String str) {
		return ValidateMM(str);
	}
	
	public String ValidateMM(String str) {
		if (str.charAt(2) == '0' && 
				str.charAt(3) >= '0' && str.charAt(3) <= '9') {
			return ValidateDD(str);
		}
		else if (str.charAt(2) == '1' && 
				str.charAt(3) >= '0' && str.charAt(3) <= '2') {
			return ValidateDD(str);
		}
		return "Invalid";
	}
	
	public String ValidateDD(String str) {
		if (str.charAt(4) == '0' && 
				str.charAt(5) >= '0' && str.charAt(5) <= '9')
		{
			return ValidateRemain(str);
		}
		else if (str.charAt(4) == '1' && 
				str.charAt(5) >= '0' && str.charAt(5) <= '9')
		{
			return ValidateRemain(str);
		}
		else if (str.charAt(4) == '2' && 
				str.charAt(5) >= '0' && str.charAt(5) <= '9')
		{
			return ValidateRemain(str);
		}
		else if (str.charAt(4) == '3' && 
				str.charAt(5) >= '0' && str.charAt(5) <= '1')
		{
			return ValidateRemain(str);
		}
		return "Invalid";
	}
	
	public String ValidateRemain(String str) {
		return str;
	}
}

public class RRNTest {
	public static void main(String[] args) {
		String str = "abc128714cd7903241081511AE@560547145666#";
		
		RRN r = new RRN();
		r.ValidateNumbers(str);
		r.Validate();
	}
}

by Regular Expression
C++pasted just now: 
import java.util.regex.Matcher;
import java.util.regex.Pattern;

class RRN {
	String rrn;
	String PatternStr = "\\d\\d(0[1-9]|1[0-2])([0-2][1-9]|3[0-1])[1-4]\\d{6}";
	//Pattern pat = Pattern.compile("\\w\\w");
	//Pattern pat = Pattern.compile("(?i)]*[src] *= *[\"\']{0,1}([^\"\'\\ >]*)");
	Pattern pat = Pattern.compile(PatternStr);

	Matcher mat;
	boolean found;

	public String FindRRN(String str) {
		mat = pat.matcher(str);
		found = mat.find();
		if (found)
			rrn = mat.group();
		else
			rrn = "Not found";
		return rrn;
	}
}

public class RRNTest {
	public static void main(String[] args) {
		String str = "abc128714cd7903241081511AE@560547145666#";
		String result;
		RRN r = new RRN();
		result = r.FindRRN(str);
		System.out.println(result);
	}
}




-end

'Java' 카테고리의 다른 글

Exception  (0) 2010.08.23
자바 주요 클래스  (0) 2010.08.19
static vs final  (0) 2010.08.17
내부 클래스 용도  (0) 2010.08.17
자바 소수점 출력  (0) 2010.08.13
And

[ShapeEx]

|
#도형 그리기
ShapeView.java
1. drawText() 이용
2. moveTo(), lineTo() 이용
package net.itisn.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Paint.Style;
import android.view.View;

public class ShapeView extends View {

	public ShapeView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.setBackgroundColor(Color.WHITE);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		// 그리기 객체 생성
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		
		// 선 그리기
		paint.setStrokeWidth(20);	// 굵기
		paint.setStyle(Style.STROKE);	// 실선
		paint.setColor(Color.argb(255, 255, 0, 255));
		canvas.drawLine(0, 0, 200, 200, paint);
		
		// Path를 이용한 그리기
		paint.setStrokeWidth(10);	// 굵기
		paint.setStyle(Style.STROKE);
		paint.setColor(Color.argb(255, 0, 255, 255));
		Path path = new Path();
		path.moveTo(255, 210);
		path.lineTo(0, 0);
		canvas.drawPath(path, paint);
		
		
		
	}
}


도형 그리기
package net.itisn.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.view.View;

public class ShapeView extends View {

	public ShapeView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.setBackgroundColor(Color.WHITE);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		// 그리기 객체 생성
		Paint paint = new Paint();
		paint.setAntiAlias(true);
		
		// 선 그리기
		paint.setStrokeWidth(20);	// 굵기
		paint.setStyle(Style.STROKE);	// 실선
		paint.setColor(Color.argb(255, 255, 0, 255));
		canvas.drawLine(0, 0, 200, 200, paint);
		
		// Path를 이용한 선 그리기
		paint.setStrokeWidth(10);
		paint.setStyle(Style.STROKE);
		paint.setColor(Color.argb(255, 0, 255, 255));
		Path path = new Path();
		path.moveTo(255, 210);
		path.lineTo(0, 0);
		canvas.drawPath(path, paint);
		
		// 사각형 그리기
		paint.setColor(Color.BLUE);
		paint.setStrokeWidth(2);
		canvas.drawRect(new Rect(100, 100, 200, 200), paint);
		canvas.drawRect(300, 20, 10, 500, paint);
		
		// 라운드 사각형 그리기
		paint.setColor(Color.argb(255, 255, 0, 255));
		canvas.drawRoundRect(new RectF(10, 10, 100, 100), 10, 10, paint);
		
		// 원 그리기
		canvas.drawCircle(50, 50, 40, paint);
	}
}



-end

'Android' 카테고리의 다른 글

[ImageView]  (0) 2010.08.17
[LifeCycle]  (0) 2010.08.17
[.java로 View Control]  (0) 2010.08.16
[RelativeLayout] 0. 레이아웃 만들기  (0) 2010.08.13
XML 문법  (0) 2010.08.13
And

[.java로 View Control]

|
#자바 파일로 작성

StringEx extends Activity {
setContentView(new StringView(this));
StringView라는 클래스의 객체를 생성하여 StringEx를 넘겨준다.
그러면 StringView는 StringEx를 받아 거기에 그림을 그리거나 글을 쓴다.
StringView는 그림을 그리거나 글을 쓸 때 onDraw()가 필요하기 때문에 View를 상속받는다.
super.onDraw(canvas);를 가장 먼저 실행한 후, 원하는 작업 수행

1. onCreate
2. onStart
3. onResume
4. setContentView(new StringView(this));

StringEx.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package net.itisn.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;

public class StringEx extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(new StringView(this));
    }
}


StringView.java
package net.itisn.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;

public class StringView extends View {

	public StringView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		this.setBackgroundColor(Color.WHITE);
	}

	//그리기 함수
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		
		//그리기 객체
		Paint paint = new Paint();
		paint.setAntiAlias(true);	//그리기 객체에 안티알리아스 적용

		//문자 크기 및 색상 설정
		paint.setTextSize(12);
		paint.setColor(Color.argb(255, 0, 0, 0));

		//폰 화면 가져와서 글자 쓰기
		canvas.drawText("화면 넓이" + this.getWidth() + 
				"화면 높이" + this.getHeight(),
				0, 30, paint);
		
		//문자열의 폭 구하기
		canvas.drawText("문자열 폭" + (int)paint.ascent(), 0, 60, paint);
		
		//문자 크기 16, 색상 빨간색 설정
		paint.setTextSize(16);
		paint.setColor(Color.argb(128, 255, 0, 0));
		
		//폰 화면(canvas)에 그리기
		canvas.drawText("두번째 문자", 0, 90, paint);
		
	}
}

'Android' 카테고리의 다른 글

[LifeCycle]  (0) 2010.08.17
[ShapeEx]  (0) 2010.08.16
[RelativeLayout] 0. 레이아웃 만들기  (0) 2010.08.13
XML 문법  (0) 2010.08.13
[CustomView] 4. Thread 이용하여 그림 움직이기  (0) 2010.08.12
And

folding

|

http://cdcsman.tistory.com/146 플러그인 정리

folding

접기 : 명령모드에서 v}zf
풀기 : zo

BufExplorer
다운로드 링크 : http://www.vim.org/scripts/script.php?script_id=42
설치 : bufexplorer.vim 파일을 vim[version]/vimfiles/plugin 아래에 복사
명령어 : vim에서 :BufExplorer 입력 (대소문자 구분, :B 누르고 탭 키 누르면 자동완성)

Taglist
다운로드 링크 : http://www.vim.org/scripts/script.php?script_id=273
설치 : taglist.vim 파일을 vim[version]/vimfiles/plugin 아래에 복사 후, 열어서 let Tlist_Auto_Open = 0 -> let Tlist_Auto_Open = 1
실행 : vim이 실행되면 자동으로 실행된다.
명령어 : Ctrl + TAB : 리스트와 에디터 이동, Enter : 해당 심볼의 위치로 이동, jk : 리스트에서 위아래 이동

자동완성
명령어 : Ctrl + p : 현재 커서의 위쪽 심볼부터 정렬/ Ctrl + n : 현재 커서의 아래쪽 심볼부터 정렬

NerdTree
드라이브 변경 : :NerdTree f:\

인텔리센스
다운로드 링크 : http://insenvim.sourceforge.net/
설치 : exe 실행




'VIM 강좌' 카테고리의 다른 글

용어 tabstop shiftwidth  (0) 2010.08.23
ctags & cscope  (0) 2010.08.15
vim 사용법  (0) 2010.06.12
And

ctags & cscope

|
1. tags 파일 생성

[path]$ ctags -R or $ make tags

2. .vimrc 파일에 추가
:set tags+=[path]/tags
ex) :set tags+=../../tags
:set tagbsearch (검색 속도 향상)

3. 명령어
:ta [name] : 첫번째 검색 결과로 이동 (==Ctrl + ])
Ctrl + t : 원래 위치로 이동
:tn : 다음 검색 결과로 이동
:tp : 이전 검색 결과로 이동
:ts [name] : 결과 리스트를 출력하여 선택한 번호로 이동
:tj [name] : 결과가 하나이면 이동, 두개 이상이면 리스트 출력

== 간단한 ctags 명령어 목록 ==
:ta [name] :: name과 일치하는 태그 위치로 이동
ctrl + ]       :: 커서가 위치하고 있는 함수나 구조체의 정의로 이동
ctrl + t        :: 이전 위치로 돌아오기
:ts [name] :: name과 일치하는 태그 목록 출력
:ta /[name]:: name과 일치하는 태그 목록 출력
:tj [name]  :: 목록이 한개인 경우 이동, 여러개인 경우 목록 출력
:tn             :: 다음 태그로 이동 (tag next)
:tp             :: 이전 태그로 이동 (tag previous)
:tags         :: 이동한 태그 히스토리 목록 출력 
==============================


1. scope.files 생성
[path]$ find ./ -name *.[chS] -print > scope.files

2. 명령어
:cs add ../../scope.files : scope.files 데이터베이스 연결
:cs show : 현재 연결된 데이터베이스 리스트 출력
:cs help : 도움말 출력
:cs find [num/char] [name]




'VIM 강좌' 카테고리의 다른 글

용어 tabstop shiftwidth  (0) 2010.08.23
folding  (0) 2010.08.15
vim 사용법  (0) 2010.06.12
And

C++ 생성자

|

C++pasted 1 second ago: 
class NeedConstructor
{
public:
	const int maxCount;
	int& ref;
	int sample;
};

int main()
{
	NeedConstructor cr;

	cr.maxCount = 100;
	cr.ref = cr.sample;

	return 0;
}

class NeedConstructor
{
public:
	const int maxCount;
	int& ref;
	int sample;

	NeedConstructor();
};

NeedConstructor::NeedConstructor()
{
	maxCount = 100;
	num = sample;
}

int main()
{
	NeedConstructor cr;

	return 0;
}

class NeedConstructor
{
public:
	const int maxCount;
	int& ref;
	int sample;

	NeedConstructor();
};

NeedConstructor::NeedConstructor()
	: maxCount(100), ref(sample)
{
	sample = 200;
}

int main()
{
	NeedConstructor cr;

	cout << "cr.maxCount = " << cr.maxCount << "\n";
	cout << "cr.ref = " << cr.ref << "\n";

	return 0;
}



-end

'C++' 카테고리의 다른 글

다중 상속의 문제점  (0) 2010.08.16
생성자와 소멸자  (0) 2010.08.13
c++ 오버라이딩  (0) 2010.07.03
동적 할당 0614  (0) 2010.06.14
c++ 0610  (0) 2010.06.10
And

자바 소수점 출력

|

double d = Double.parseDouble(String.format("%.3f", 1.4455555));
 System.out.println(d);

'Java' 카테고리의 다른 글

Exception  (0) 2010.08.23
자바 주요 클래스  (0) 2010.08.19
static vs final  (0) 2010.08.17
내부 클래스 용도  (0) 2010.08.17
주민등록번호 추출  (0) 2010.08.16
And

[RelativeLayout] 0. 레이아웃 만들기

|

#RelativeLayout
RelativeLayoutTest.java
1. findViewById()로 버튼 객체 선택. final로 선언되어 있어야 함.
2. 버튼에 이벤트 리스너 설정.
package net.itisn.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class RelativeLayoutTest2 extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//리소스에서 버튼을 가져옴
		final Button buttonCancel = (Button)this.findViewById(R.id.ButtonCancel);
		//리소스에서 에디트텍스트를 가져옴
		final EditText editText = (EditText)this.findViewById(R.id.EditText01);

		//취소 버튼에 이벤트 추가
		buttonCancel.setOnClickListener(new OnClickListener() {

			@Override//클릭했을 때 에디트텍스트에 문자열 출력
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				editText.setText("Button is Pushed.");
			}

		});
	}
}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
>
	<TextView
		android:text="@+id/TextView01"
		android:id="@+id/TextView01"
		android:layout_height="wrap_content"
		android:layout_width="fill_parent"
	></TextView>
	<EditText
		android:text="@+id/EditText01"
		android:id="@+id/EditText01"
		android:layout_below="@id/TextView01"
		android:layout_height="wrap_content"
		android:layout_width="fill_parent"
	></EditText>
	<Button
		android:layout_below="@id/EditText01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Cancel"
		android:id="@+id/ButtonCancel"
	></Button>
	<Button
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="OK"
		android:id="@+id/ButtonOK"
		android:layout_below="@+id/EditText01"
		android:layout_toRightOf="@+id/ButtonCancel"
	></Button>
</RelativeLayout>



- END -

'Android' 카테고리의 다른 글

[ShapeEx]  (0) 2010.08.16
[.java로 View Control]  (0) 2010.08.16
XML 문법  (0) 2010.08.13
[CustomView] 4. Thread 이용하여 그림 움직이기  (0) 2010.08.12
[CustomView] 3. RobotView 그림 위치 지정 - 성공  (0) 2010.08.12
And

생성자와 소멸자

|
생성자
클래스와 동일한 이름
반환 값이 없다.
객체가 생성될 때 자동으로 호출된다.
생성자를 작성하지 않으면 기본 생성자가 자동으로 호출된다. Class::Class() {}
Point::Point() { _x = 0; _y = 0; }
Point pt;
Point pt = Point();

디폴트 생성자
인자가 없는 생성자 Class::Class() { initialize code; }
Point pt;
Point pt = Point();

인자가 있는 생성자
Point::Point(int x, int y) {_x = x; _y = y; }
Point pt(10, 20);

복사 생성자
자신과 동일한 타입의 객체에 대한 레퍼런스를 인자로 받는 생성자.
Class::Class(Class& c) { intialize code; }
Class::Class(const Class& c) { intialize code; } 권장
Point::Point(const Point& pt) { x = pt.x; y = pt.y; }
Point pt1;
Point pt2 = pt1; (초기화 문법 이용)
Point pt2(pt1); (생성자 호출 문법 이용)
*초기화 : 생성과 동시에 값을 대입하는 것???
Point pt1;
Point pt2;
pt2 = pt1; 복사 생성자가 호출되지 않고, 멤버변수를 1:1로 복사한다.

class string
{
private:
char* p;
public:
string(const string& s);
int size() const
{
return strlen(p);
}
...

Shallow Copy
string::string(const string& s) { p = s.p; }
string str1;
string str2(str1);
str1 객체의 문자열의 시작 주소만 복사된다. str1 객체가 소멸되면 str1이 가리키고 있던 문자열도 소멸되므로 str2는???
Deep Copy
string::string(const string& s) { p = new char[s.Size() + 1]; strcpy(p, s.p);
string str1;
string str2(str1);
str1 객체의 문자열 자체를 복사한다. str1 객체가 소멸되어도 str2 객체는 새로 생성된 문자열의 시작주소를 가리키므로 문제없다.

반드시 생성자가 필요한 경우 : const, &
const : 한 번 정의된 이후에는 값을 변경할 수 없으므로 반드시 초기화하여 그 값만을 가져야 한다.
& : 처음 정의할 때 참조한 변수 이외의 다른 변수는 참조할 수 없으므로 반드시 초기화해야 한다.

class NeedConstructor
{
public:
const int maxCount;
int& ref;
int sample;

NeedConstructor();
NeedConstructor(int count, int& number);
};

NeedConstructor::NeedConstructor()
: maxCount(100), ref(sample)
{
sample = 200;
}

NeedConstructor::NeedConstructor(int count, int& number)
: maxCount(count), ref(number0
{
sample = 200;
}

생성자를 이용한 임시 객체
void Func(const Point& pt)
{
...
}
Func(Point(x, y));

소멸자
DynamicArray::DynamicArray(int arraySize)
{
arr = new int [arraySize];
}

DynamicArray::~DynamicArray()
{
delete [] arr;
arr = NULL;
}

main() 죵료시 함수 내의 객체도 소멸되므로 소멸자를 호출하고 이 때 메모리를 해제한다. 













import android.view.View.oonclickelisterne;

setContentView(R.laout.hello_layout);

EditText edittext = (EditiText)this.findViewById(R.id.EditText01);
Button button = (button)this.findViewById(R.id....);
button.setonclickelistenter(new onclicklistener() {

 } )

public onClick(View arg0) {
edittext.setText("버튼 눌러짐"); << final 처리 변수 -- final EditText edit~~~

'C++' 카테고리의 다른 글

다중 상속의 문제점  (0) 2010.08.16
C++ 생성자  (0) 2010.08.13
c++ 오버라이딩  (0) 2010.07.03
동적 할당 0614  (0) 2010.06.14
c++ 0610  (0) 2010.06.10
And

XML 문법

|
선언
<?xml version="버전 번호" encoding="인코딩 방식" standalone="yes|no"?>
<와 ?와 xml 사이에 공백이 있으면 안됨.

standalone
작성된 XML 문서를 XML 파서가 해석할 때 외부 DTD 문서를 참고해야 한다는 것을 XML 파서에게 알려주기 위한 목적
yes : DTD 문서를 참고하지 않고 XML 문서 해석
no : DTD 문서를 참고하여 XML 문서 해석
보통 생략하는데 생략시 no로 설정됨

DOM : 전체를 읽어서 추출
SAX : 파일을 읽으면서 처리

Ctrl + Shift + F : 자동으로 정렬, 옵션을 줄 수 있다.
Ctrl + I : 자동으로 정렬

XML 소스 정렬
Preference - XML - Editor - Split, Align


xmlns 네임스페이스
xmlns:android="http://schemas.android.com/apk/res/android"

android 네임스페이스
android:layout_width="fill_parent"

string.xml : Add > name, value 작성
main.xml : Text 태그의 android:id="@+id/text" -> android:text="@string/my_name"

And

[CustomView] 4. Thread 이용하여 그림 움직이기

|
#Thread 이용하여 그림 움직이기

[RobotView.java]
package net.itisn.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class RobotView extends View implements Runnable {
    private final static int STEP = 10;
    private Drawable image;
    private int viewWidth, viewHeight;
    private int imageWidth, imageHeight;
    private int x, y;

    public RobotView(Context context, AttributeSet attrs) {
    	super(context, attrs);
    	// TODO Auto-generated constructor stub
    	image = this.getResources().getDrawable(R.drawable.su);

    	Thread thread = new Thread(this);
    	thread.start();
    }

    @Override
    protected void onDraw(Canvas canvas) {
    	// TODO Auto-generated method stub
    	image.setBounds(x, y, x + imageWidth, y + imageHeight);
    	image.draw(canvas);

    	super.onDraw(canvas);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    	// TODO Auto-generated method stub
    	viewWidth = this.getWidth();
    	viewHeight = this.getHeight();

    	imageWidth = image.getIntrinsicWidth();
    	imageHeight = image.getIntrinsicHeight();

    	x = viewWidth / 2 - imageWidth / 2;
    	y = viewHeight / 2 - imageHeight / 2;

    	super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    public void run() {
    	// TODO Auto-generated method stub
    	for (; ;) {
    		try {
    			Thread.sleep(500);
    			y = Math.min(viewHeight - imageHeight, y + STEP);
    			this.postInvalidate();
    		} catch(InterruptedException e) {
    			e.printStackTrace();
    		}
    	}
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
    	// TODO Auto-generated method stub
    	x = (int)event.getX();
    	y = (int)event.getY();
    	this.invalidate();

    	return super.onTouchEvent(event);
    }
}

[main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

<net.itisn.test.RobotView
    android:id="@+id/su"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    />

</LinearLayout>



sleep을 쓸 경우 InterrupedException 예외 발생
따라서 try catch 문을 반드시 써주어야 함

static 클래스는 new 연산자 없이 바로 사용가능. 
Math.min
System.out.println(); 
원래 System sys = new System();
sys.out.println()

postInvalidate() 화면을 새로 그림..

ontouchEvent
x = (int)event.getx();
y = (int)event.gety();

this.invalidate();

return true;

- END

'Android' 카테고리의 다른 글

[RelativeLayout] 0. 레이아웃 만들기  (0) 2010.08.13
XML 문법  (0) 2010.08.13
[CustomView] 3. RobotView 그림 위치 지정 - 성공  (0) 2010.08.12
[CustomView] 1. 그림 정가운데 출력  (0) 2010.08.12
[CustomView] 0. RobotView 생성  (0) 2010.08.11
And

[CustomView] 3. RobotView 그림 위치 지정 - 성공

|
#onSizeChanged()에서 그림 위치 셋팅 - 그림이 정상적으로 그려짐
[RobotView.java]
onSizeChanged()를 오버라이드하여 그 안에 작성한다.
package net.itisn.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

public class RobotView extends View {

    private Drawable image;
    private int viewWidth, viewHeight;
    private int imageWidth, imageHeight;
    private int x, y;

    public RobotView(Context context, AttributeSet attrs) {
    	super(context, attrs);
    	// TODO Auto-generated constructor stub
    	image = this.getResources().getDrawable(R.drawable.su);
    }

    @Override
    protected void onDraw(Canvas canvas) {
    	// TODO Auto-generated method stub
    	image.draw(canvas);
    	super.onDraw(canvas);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    	// TODO Auto-generated method stub
    	viewWidth = this.getWidth();
    	viewHeight = this.getHeight();

    	imageWidth = image.getIntrinsicWidth();
    	imageHeight = image.getIntrinsicHeight();

    	x = viewWidth / 2 - imageWidth / 2;
    	y = viewHeight / 2 - imageHeight / 2;
    	image.setBounds(x, y, x + imageWidth, y + imageHeight);

    	super.onSizeChanged(w, h, oldw, oldh);
    }
}

[main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

<net.itisn.test.RobotView
    android:id="@+id/su"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    />

</LinearLayout>

'Android' 카테고리의 다른 글

[RelativeLayout] 0. 레이아웃 만들기  (0) 2010.08.13
XML 문법  (0) 2010.08.13
[CustomView] 4. Thread 이용하여 그림 움직이기  (0) 2010.08.12
[CustomView] 1. 그림 정가운데 출력  (0) 2010.08.12
[CustomView] 0. RobotView 생성  (0) 2010.08.11
And

[CustomView] 1. 그림 정가운데 출력

|
#RobotView 이미지 가운체 드로우
[RobotView.java]
package net.itisn.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

public class RobotView extends View {

    private Drawable image;

    public RobotView(Context context, AttributeSet attrs) {
    	super(context, attrs);
    	// TODO Auto-generated constructor stub
    	image = this.getResources().getDrawable(R.drawable.su);
    }

    @Override
    protected void onDraw(Canvas canvas) {
    	// TODO Auto-generated method stub
    	int viewWidth = this.getWidth();
    	int viewHeight = this.getHeight();

    	int imageWidth = image.getIntrinsicWidth();
    	int imageHeight = image.getIntrinsicHeight();

    	int x = viewWidth / 2 - imageWidth / 2;
    	int y = viewHeight / 2 - imageHeight / 2;

    	image.setBounds(x, y, x + imageWidth, y + imageHeight);
    	image.draw(canvas);

    	super.onDraw(canvas);
    }
}

[main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

<net.itisn.test.RobotView
    android:id="@+id/su"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />

</LinearLayout>

- END -

And

1일차

|
#부트 이미지 - Binary
helloos.img
0000:0000 EB 4E 90 48 45 4C 4C 4F-49 50 4C 00 02 01 01 00
0000:0010 02 E0 00 40 0B F0 09 00-12 00 02 00 00 00 00 00
0000:0020 40 0B 00 00 00 00 29 FF-FF FF FF 48 45 4C 4C 4F
0000:0030 2D 4F 53 20 20 20 46 4C-54 31 32 20 20 20 00 00
0000:0040 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0050 B8 00 00 8E D0 BC 00 7C-8E D8 8E C0 BE 74 7C 8A
0000:0060 04 83 C6 01 3C 00 74 09-B4 0E BB 0F 00 CD 10 EB
0000:0070 EE F4 EB FD 0A 0A 68 65-6C 6C 6F 2C 20 88 6F 72
0000:0080 6C 64 0A 00 00 00 00 00-00 00 00 00 00 00 00 00

0000:0090 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:00A0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:00B0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:00C0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:00D0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:00E0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:00F0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0100 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0110 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0120 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0130 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0140 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0150 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0160 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0170 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0180 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:0190 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:01A0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:01B0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:01C0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:01D0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0000:01E0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00

0000:01F0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 55 AA
0000:0200 F0 FF FF 00 00 00 00 00-00 00 00 00 00 00 00 00

0000:0210 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
~
0000:13F0 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00

0000:1400 F0 FF FF 00 00 00 00 00-00 00 00 00 00 00 00 00

0000:1410 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
~
0016:7FFF 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00
0016:8000


#부트 이미지 - Assembly
helloos.nas
DB 0xeb, 0x4e, 0x90, 0x48, 0x45, 0x4c, 0x4c, 0x4f
DB 0x02, 0xe0, 0x00, 0x40, 0x0b, 0xf0, 0x09, 0x00
DB 0x40, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x29, 0xff
DB 0xff, 0xff, 0xff, 0x48, 0x45, 0x4c, 0x4c, 0x4f
DB 0x2d, 0x4f, 0x53, 0x20, 0x20, 0x20, 0x46, 0x4c
DB 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0xb8, 0x00, 0x00, 0x8e, 0xd0, 0xbc, 0x00, 0x7c
DB 0x8e, 0xd8, 0x8e, 0xc0, 0xbe, 0x74, 0x7c, 0x8a
DB 0x04, 0x8., 0xc6, 0x01, 0x3c, 0x00, 0x74, 0x09
DB 0xb4, 0x0e, 0xbb, 0x0f, 0x00, 0xcd, 0x10, 0xeb
DB 0xee, 0xf4, 0xeb, 0xfd, 0x0a, 0x0a, 0x68, 0x65
DB 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x88, 0x6f, 0x72
DB 0x6c, 0x64, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00

DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00

DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa

DB 0xf0, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
~ (약 18만 행)
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00

#부트 이미지 - 개선된 Assembly
helloos.nas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
DB 0xeb, 0x4e, 0x90, 0x48, 0x45, 0x4c, 0x4c, 0x4f
DB 0x02, 0xe0, 0x00, 0x40, 0x0b, 0xf0, 0x09, 0x00
DB 0x40, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x29, 0xff
DB 0xff, 0xff, 0xff, 0x48, 0x45, 0x4c, 0x4c, 0x4f
DB 0x2d, 0x4f, 0x53, 0x20, 0x20, 0x20, 0x46, 0x4c
DB 0x54, 0x31, 0x32, 0x20, 0x20, 0x20, 0x00, 0x00
RESB 16
DB 0xb8, 0x00, 0x00, 0x8e, 0xd0, 0xbc, 0x00, 0x7c
DB 0x8e, 0xd8, 0x8e, 0xc0, 0xbe, 0x74, 0x7c, 0x8a
DB 0x04, 0x8., 0xc6, 0x01, 0x3c, 0x00, 0x74, 0x09
DB 0xb4, 0x0e, 0xbb, 0x0f, 0x00, 0xcd, 0x10, 0xeb
DB 0xee, 0xf4, 0xeb, 0xfd, 0x0a, 0x0a, 0x68, 0x65
DB 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x88, 0x6f, 0x72
DB 0x6c, 0x64, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00
RESB 368
DB 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0xaa
DB 0xf0, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00
RESB 4600
DB 0xf0, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00
RESB 1469432


#부트 이미지 - 더욱 개선된 Assembly
helloos.nas
;hello-os
;이하는 표준적인 FAT12 포맷 플로피디스크를 위한 서술
DB    0xeb, 0x4e, 0x90
DB    "HELLOIPL"    ;부트섹터의 이름을 자유롭게 써도 좋음
DW    512    	;1섹터의 크기
DB    1    	;클러스터의 크기 (1섹터로 해야 함)
DW    1    	;예약된 섹터의 수
DB    2    	;디스크의 FAT 테이블의 수
DW    224    	;루트 디렉토리 엔트리의 수 (보통은 224엔트리)
DW    2880    	;디스크의 총 섹터 수 (2880섹터로 해야 함)
DB    0xf0    	;미디어 타입 (0xf0으로 해야 함)
DW    9    	;하나의 FAT 테이블의 섹터 수 (9섹터로 해야 함)
DW    18    	;1트랙의 섹터 수 (18로 해야 함)
DW    2    	;헤드의 수 (2로 해야 함)
DD    0    	;파티션을 사용하지 않으므로 이곳은 반드시 0
DB    0, 0, 0x29    ;잘 모르겠지만 이 값을 넣어 두면 좋다고 함
DD    0xffffffff    ;아마 볼륨의 시리얼 번호
DB    "HELLO-OS"    ;디스크의 이름
DB    "FAT12   "    ;포맷의 이름 (8바이트)
RESB    18    	;어쨋든 18바이트 남겨둠

;프로그램 본체
DB    0xb8, 0x00, 0x00, 0x8e, 0xd0, 0xbc, 0x00, 0x7c
DB    0x8e, 0xd8, 0x8e, 0xc0, 0xbe, 0x74, 0x7c, 0x8a
DB    0x04, 0x83, 0xc6, 0x01, 0x3c, 0x00, 0x74, 0x09
DB    0xb4, 0x0e, 0xbb, 0x0f, 0x00, 0xcd, 0x10, 0xeb
DB    0xee, 0xf4, 0xeb, 0xfd

;메시지 부분
DB    0x0a, 0x0a    ;줄바꿈 2개
DB    "hello, world"
DB    0x0a    	;줄바꿈
DB    0

RESB    0x1fe-$    	;0x001fe(510바이트, 0x001fe 앞)까지 0x00으로 채움
DB    0x55, 0xaa

;이하는 부트섹터 이외의 부분에 기술
DB    0xf0, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00
RESB    4600
DB    0xf0, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00
RESB    1469432

- END -
And

[CustomView] 0. RobotView 생성

|
#CustomView 만들기

View(Context context, AttributeSet attrs) {}
1. 안드로이드 OS의 현재 상태 정보를 관리하는 클래스
2. 속성 배열

java.lang.Object
ㄴandroid.content.Context

java.lang.Object
ㄴandroid.content.Context
  ㄴandroid.content.ContextWrapper
    ㄴandroid.view.ContextThemeWrapper
      ㄴandroid.app.Activity

Context는 OS입장에서 실행 중인 application을 관리하기 위한 자료구조라고 보시면 될 것 같습니다. 
Class를 생성할 때 또는 정보를 얻고자 할때 context가 parameter로 많이 사용이 되는데 
이는 Class memory를 할당하거나 정보를 얻고자 하는 memory block 정보를 검색하기 위해서 
어떠한 application에서 요청했는지가 필요하기 때문입니다. 

예를들어서 TextView를 생성하는 경우 내부적으로는 heap memory를 할당하고 
해당 memory pointer를 Application context 정보를 기반으로 관리하는 것이고 
Application이 종료하게 되면 해당 application이 사용하는 heap memory를 free하는데 사용합니다. 

AttributeSet은 일반적으로 layout xml에서 android:text="@string/hello"와 같이 설정을 하는데 
LayoutInflater class를 사용해서 TextView를 실시간으로 생성하게 되는 경우 
TextView의 속성을 지정할 때 사용하는 class입니다. 

AttributeSet은 SDK를 보시면 아시겠지만 XML에 기반한 class입니다.


[개요]
1. MyView Class 추가
SuperClass : android.view.View 선택
2. MyView(Context context, AttributeSet attrs) 생성자 추가
View 클래스는 반드시 생성자를 필요로 한다.
x 클릭 > 2번째 생성자 선택
3. 우클릭 > Source > Override 선택 (Alt + Shift + S > v)
onDraw() 선택
위치 지정
4. 그림 정보를 담을 image 변수 생성
private Drawable image; (자동 임포트 : Ctrl + Shift + O)
생성자 안의 super() 아래에서 image에 그림의 아이디를 할당 (R.java에 모든 리소스들이 자동 생성됨)
5. onDraw() 안의 super() 위에서 image 위치 지정 및 그리기
6. main.xml에 태그 삽입
@+id/myview_id : 새로운 아이디 생성하여 사용
@id/myview_id : 기존 아이디 사용
직접 생선한 클래스이므로 디자이너에는 없다. 따라서 직접 xml 코드를 작성해 주어야 한다.
특정 동작을 하는 애니메이션 같은 경우에 커스텀 뷰를 만들어 사용한다.

[RobotView.java]
package net.itisn.test;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

public class RobotView extends View {

    private Drawable image;

    public RobotView(Context context, AttributeSet attrs) {
    	super(context, attrs);
    	// TODO Auto-generated constructor stub
    	image = this.getResources().getDrawable(R.drawable.su);
    }

    @Override
    protected void onDraw(Canvas canvas) {
    	// TODO Auto-generated method stub
    	image.setBounds(0, 0, 128, 128);
    	image.draw(canvas);
    	//layout(0, 0, 128, 128);

    	super.onDraw(canvas);
    }
}

[main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />

<net.itisn.test.MyView android:id="@+id/su"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
<net.itisn.test.SunView
    android:id="@+id/icon"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    />

</LinearLayout>

And

C# 기본

|
기본 출력
using System;

class MainClass
{
    public static void Main()
    {
        Console.WriteLine("A simple C# program.");
    }
}

메인함수 인자 반복 출력
using System;

class MainClass
{
    public static void Main(string[] args)
    {
        foreach (string arg in args)
            Console.WriteLine("Arg: {0}", arg);
    }
}

메인함수 리턴
using System;

class MainClass
{
    public static int Main()
    {
        Console.WriteLine("Hello, Universe!");
        return (0);
    }
}

메인함수 4가지 형태
using System;

class MainClass
{
    static void Main()
    {
    }

    static int Main()
    {
    }

    static void Main(string[] args)
    {
    }

    static int Main(string[] args)
    {
    }
}

인자 옵션 사용 여부 확인
class MainClass
{
    static void Main(string[] args)
    {
        if (args[0][0] == '-')
        {
            System.Console.WriteLine("-");
        }
    }
}

WriteLine 문자열 안에 변수 사용
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("{0} command line arguments were specified:", args.Length);
        foreach (string arg in args)
            Console.WriteLine(arg);
    }
}

네임스페이스
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("A simple C# program.");
        System.Console.WriteLine("A simple C# program.");
    }
}

네임스페이스 사용, [STAThread]
기본적으로, VS .NET에 의해 만들어진 응용 프로그램의 Main()메소드에는 [STAThread] 어트리뷰트가 첨가되어 있다. 
이 어트리뷰트는 해당 응용 프로그램이 COM형식을 이용하는 경우에 (단지 이 경우에만 해당하는 것인데) 해당 응용 프로그램이 
단일 스레드 아파트(single threaded apartment, STA) 모델로 설정되어야 한다는 것을 런타임에게 알려주는 역할을 한다. 
해당 응용 프로그램에서 COM 형식을 이용하지 않는다면, [STAThread] 어트리뷰트는 무시되기 때문에 삭제해도 무방하다.
using System;

namespace HelloWorld
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class Class1
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            System.Console.WriteLine("Hello world from C#");
        }
    }
}

네임스페이스 안에 들어 있는 클래스 객체 생성
using System;

namespace Counter
{
    class MyClass
    {
    }
}

class MainClass
{
    public static void Main()
    {
        Counter.MyClass my = new Counter.MyClass();
    }
}

네임스페이스 별명 사용
using ThatConsoleClass = System.Console;

class MainClass
{
    public static void Main()
    {
        ThatConsoleClass.WriteLine("Hello");
    }
}

네임스페이스 안의 클래스 사용하여 출력
using System;

namespace Counter
{
    class MyClass
    {
        public MyClass()
        {
            Console.WriteLine("Counter1 namespace.");
        }
    }
}

namespace Counter2
{
    class MyClass
    {
        public MyClass()
        {
            Console.WriteLine("Counter2 namespace.");
        }
    }
}

class MainClass
{
    public static void Main()
    {
        Counter.MyClass m1 = new Counter.MyClass();

        Counter2.MyClass m2 = new Counter2.MyClass();
    }
}

네임스페이스를 나누어서 클래스 정의 가능
using System;

using Counter;

namespace Counter
{
    class MyClass
    {
    }
}

namespace Counter
{
    class MySecondClass
    {
    }
}

class MainClass
{
    public static void Main()
    {
        MyClass m = new MyClass();
        MySecondClass cu = new MySecondClass();
    }
}

네스티디 네임스페이스
using System;

namespace NS1
{
    class ClassA
    {
        public ClassA()
        {
            Console.WriteLine("constructing ClassA");
        }
    }
    namespace NS2
    {
        class ClassB
        {
            public ClassB()
            {
                Console.WriteLine("constructing ClassB");
            }
        }
    }
}

class MainClass
{
    public static void Main()
    {
        NS1.ClassA a = new NS1.ClassA();

        NS1.NS2.ClassB b = new NS1.NS2.ClassB();
    }
}

네임스페이스 별명, :: 사용
using System;

using Counter;
using AnotherCounter;

using Ctr = Counter;

namespace Counter
{
    class MyClass
    {
    }
}

namespace AnotherCounter
{
    class MyClass
    {
    }
}

class MainClass
{
    public static void Main()
    {
        Ctr::MyClass m = new Ctr::MyClass();
    }
}

네임스페이스.클래스 오브젝트 = new 네임스페이스.생성자();
namespace CompanyName
{
    public class Car
    {
        public string make;
    }
}

namespace DifferentCompany
{
    public class Car
    {
        public string make;
    }
}

class MainClass
{
    public static void Main()
    {
        System.Console.WriteLine("Creating a CompanyName.Car object");
        CompanyName.Car myCar = new CompanyName.Car();
        myCar.make = "Toyota";
        System.Console.WriteLine("myCar.make = " + myCar.make);

        System.Console.WriteLine("Creating a DifferentCompany.Car object");
        DifferentCompany.Car myOtherCar = new DifferentCompany.Car();
        myOtherCar.make = "Porsche";
        System.Console.WriteLine("myOtherCar.make = " + myOtherCar.make);
    }
}

네임스페이스 계층...
namespace CompanyName
{
    namespace UserInterface
    {
        public class MyClass
        {
            public void Test()
            {
                System.Console.WriteLine("UserInterface Test()");
            }
        }
    }
}

namespace CompanyName.DatabaseAccess
{
    public class MyClass
    {
        public void Test()
        {
            System.Console.WriteLine("DatabaseAccess Test()");
        }
    }
}

class MainClass
{
    public static void Main()
    {
        CompanyName.UserInterface.MyClass myUI = new CompanyName.UserInterface.MyClass();
        CompanyName.DatabaseAccess.MyClass myDB = new CompanyName.DatabaseAccess.MyClass();

        CompanyName.DatabaseAccess.MyClass myMT = new CompanyName.DatabaseAccess.MyClass();

        myUI.Test();
        myDB.Test();
        myMT.Test();
    }
}

-------pause 1.5.15-----

-------start 5장 문자열-----

문자열 선언
using System;

class MainClass
{
    static void Main(string[] args)
    {
        string MyString = "Hello World";
        string Path = @"c:\Program Files";
        string Path2 = "c:\\Program Files";

        string Name = "Joe";
    }
}

문자열 인자로 넘겨서 변환 -> 복사되어 원본은 변경 안됨
using System;

class MainClass
{
    static void Main(string[] args)
    {
        string strOriginal = "Original String";
        Console.WriteLine("Value of strOriginal before call: {0}", strOriginal);

        TryToAlterString(strOriginal);

        Console.WriteLine("Value of strOriginal after call: {0}", strOriginal);
    }

    static void TryToAlterString(string str)
    {
        str = "Modified string";
    }
}

문자열 대분자로 변환, 복사되어 변환, 원본은 그대로
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string s1 = "This is my string.";
        Console.WriteLine("s1 = {0}", s1);

        string upperString = s1.ToUpper();
        Console.WriteLine("upperString = {0}", upperString);

        Console.WriteLine("s1 = {0}", s1);

        string s2 = "My other string";
        s2 = "New string value";
    }
}

빈 문자열 생성
using System;
using System.IO;
using System.Text;

public class MainClass
{
    public static void Main(String[] args)
    {
        string address = String.Empty;
    }
}

문자열을 한 문자씩 출력
using System;

class MainClass
{
    public static void Main()
    {
        string myString = "To be or not to be";

        for (int count = 0; count < myString.Length; count++)
        {
            Console.WriteLine("myString(" + count + "] = " + myString[count]);
        }
    }
}

문자열 비교, 같으면 0, 앞이면 -1, 뒤면 1, 비교시 대소문자 구분, 일부 문자열만 비교
using System;

class MainClass
{
    public static void Main()
    {
        int result;
        result = String.Compare("bbc", "abc");
        Console.WriteLine("String.Compare(\"bbc\", \"abc\" = " + result);

        result = String.Compare("abc", "bbc");
        Console.WriteLine("String.Compare(\"abc\", \"bbc\" = " + result);

        result = String.Compare("bbc", "bbc");
        Console.WriteLine("String.Compare(\"bbc\", \"bbc\" = " + result);

        result = String.Compare("bbc", "BBC", true);
        Console.WriteLine("String.Compare(\"bbc\", \"BBC\", true = " + result);

        result = String.Compare("bbc", "BBC", false);
        Console.WriteLine("String.Compare(\"bbc\", \"BBC\", false = " + result);

        result = String.Compare("Hello World", 6, "Goodbye World", 8, 5);
        Console.WriteLine("String.Compare(\"Hello World\", 6, " + "\"Goodbye World\", 8, 5) = " + result);
    }
}

문자열 합치기
using System;

class MainClass
{
    public static void Main()
    {
        string myString4 = String.Concat("A, ", "B");
        Console.WriteLine("String.Concat(\"A, \", \"B\") = " + myString4);

        string myString5 = String.Concat("A, ", "B ", "and countrymen");
        Console.WriteLine("String.concat(\"A, \", \"B \", " + "\"and countrymen\") = " + myString5);
    }
}

문자열 합치기 +연산자
using System;

class MainClass
{
    public static void Main()
    {
        string myString6 = "To be, " + "or not to be";
        Console.WriteLine("\"To be, \" + \"or not to be\" = " + myString6);
    }
}

문자열 복사 String.Copy() 이용
using System;

class MainClass
{
    public static void Main()
    {
        string myString4 = "string4";
        Console.WriteLine("myString4 = " + myString4);

        Console.WriteLine("Copying myString4 to myString7 using Copy()");

        string myString7 = String.Copy(myString4);
        Console.WriteLine("myString7 = " + myString7);
    }
}

문자열 비교 String.Equals(str1, str2), str1.Equals(str2), str1 == str2
using System;

class MainClass
{
    public static void Main()
    {
        bool boolResult;
        string myString = "str";
        string myString2 = "str2";

        boolResult = String.Equals("bbc", "bbc");
        Console.WriteLine("String.Equals(\"bbc\", \"bbc\") is " + boolResult);

        boolResult = myString.Equals(myString2);
        Console.WriteLine("myString.Equals(myString2) is " + boolResult);

        boolResult = myString == myString2;
        Console.WriteLine("myString == myString2 is " + boolResult);
    }
}

문자열 형식 지정
using System;

class MainClass
{
    public static void Main()
    {
        float myFloat = 1234.56789f;
        string myString8 = String.Format("{0, 10:f3}", myFloat);
        Console.WriteLine("String.Format(\"{0, 10:f3}\", myFloat) = " + myString8);
    }
}

문자열 합치기. "." 대신 "", " " 등 사용 가능
using System;

class MainClass
{
    public static void Main()
    {
        string[] myStrings = { "To", "be", "or", "not", "to", "be" };
        string myString9 = String.Join(".", myStrings);
        Console.WriteLine("myString9 = " + myString9);
    }
}

문자열 나누기
using System;

class MainClass
{
    public static void Main()
    {
        string[] myStrings = { "To", "be", "or", "not", "to", "be" };
        string myString9 = String.Join(".", myStrings);
        myStrings = myString9.Split('.');
        foreach (string mySplitString in myStrings)
        {
            Console.WriteLine("mySplitString = " + mySplitString);
        }
    }
}

문자열에서 문자의 인덱스 추출
using System;

class MainClass
{
    public static void Main()
    {
        string[] myStrings = { "To", "be", "or", "not", "to", "be" };
        string myString = String.Join(".", myStrings);

        char[] myChars = { 'b', 'e' };
        int index = myString.IndexOfAny(myChars);
        Console.WriteLine("'b' and 'e' occur at index " + index + " of myString");
        index = myString.LastIndexOfAny(myChars);
        Console.WriteLine("'b' and 'e' last occur at index " + index + " of myString");
    }
}

문자열 추가, 삭제, 치환(대소문자 일치해야 함)
using System;

class MainClass
{
    public static void Main()
    {
        string[] myStrings = { "To", "be", "or", "not", "to", "be" };
        string myString = String.Join(".", myStrings);

        string myString10 = myString.Insert(6, "A, ");
        Console.WriteLine("myString.Insert(6, \"A, \") = " + myString10);

        string myString11 = myString10.Remove(14, 7);
        Console.WriteLine("myString10.Remove(14, 7) = " + myString11);

        string myString12 = myString11.Replace(',', '?');
        Console.WriteLine("myString11.Replace(',', '?') = " + myString12);

        string myString13 = myString12.Replace("to be", "Or not to be A");
        Console.WriteLine("myString12.Replace(\"to be\", \"Or not to be A\") = " + myString13);
    }
}

문자열 좌우에 공백, 또는 문자 채우기
using System;

class MainClass
{
    public static void Main()
    {
        string[] myStrings = { "To", "Be", "or", "not", "to", "be" };
        string myString = String.Join(".", myStrings);

        string myString14 = '(' + myString.PadLeft(20) + ')';
        Console.WriteLine("'(' + myString.PadLeft(20) + ')' = " + myString14);

        string myString15 = '(' + myString.PadLeft(20, '.') + ')';
        Console.WriteLine("'(' + myString.PadLeft(20, '.') = " + myString15);

        string myString16 = '(' + myString.PadRight(20) + ')';
        Console.WriteLine("'(' + myString.PadRight(20) + ')' = " + myString16);

        string myString17 = '(' + myString.PadRight(20, '|') + ')';
        Console.WriteLine("'(' + myString.PadRight(20, '|') + ')' = " + myString17);
    }
}

문자열 양 끝 잘라내기, 문자 배열을 인자로 가질 수 있음
using System;

class MainClass
{
    public static void Main()
    {
        string myString18 = '(' + "  Whitespace  ".Trim() + ')';
        Console.WriteLine("'(' + \"  Whitespace  \".Trim() + ')' = " + myString18);

        string myString19 = '(' + "  Whitespace  ".TrimStart() + ')';
        Console.WriteLine("'(' + \"  Whitespace  \".TrimStart() + ')' = " + myString19);

        string myString20 = '(' + "  Whitespace  ee".TrimEnd(new char[] {'e', ' '}) + ')';
        Console.WriteLine("'(' + \"  Whitespace  \".TrimEnd() + ')' = " + myString20);
    }
}




























--------------------------------------http://csharpcomputing.com/Tutorials/Lesson9.htm---------------------------------------

파일 입출력 기본
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            if(File.Exists("test.txt"))
            {
                string content = File.ReadAllText("test.txt");
                Console.WriteLine("Current content of file:");
                Console.WriteLine(content);
            }
            Console.WriteLine("Please enter new content for the file:");
            string newContent = Console.ReadLine();
            File.WriteAllText("test.txt", newContent);
        }
    }
}

파일 입출력 스트림 이용
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            if (File.Exists("test.txt"))
            {
                string content = File.ReadAllText("test.txt");
                Console.WriteLine("Current content of file:");
                Console.WriteLine(content);
            }
            Console.WriteLine("Please enter new content for the file:");
            using (StreamWriter sw = new StreamWriter("test.txt"))
            {
                string newContent = Console.ReadLine();
                while (newContent != "exit")
                {
                    sw.Write(newContent + Environment.NewLine);
                    newContent = Console.ReadLine();
                }
            }
        }
    }
}

파일 삭제, ReadKey() 문자 입력( 콘솔 화면 멈춤용으로 사용)
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            if (File.Exists("test.txt"))
            {
                File.Delete("test.txt");
                if (File.Exists("test.txt") == false)
                {
                    Console.WriteLine("File deleted...");
                }
            }
            else
            {
                Console.WriteLine("File test.txt does not yet exist!");
            }
            Console.ReadKey();
        }
    }
}

디렉토리 삭제
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            if (Directory.Exists("testdir"))
            {
                Directory.Delete("testdir");
                if (Directory.Exists("testdir") == false)
                    Console.WriteLine("Directory deleted...");
            }
            else
                Console.WriteLine("Directory testdir does not yet exist!");
        }
    }
}

파일 이름 변경
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            if (File.Exists("test.txt"))
            {
                Console.WriteLine("Please enter a new name for this file:");
                string newFilename = Console.ReadLine();
                if (newFilename != String.Empty)
                {
                    File.Move("test.txt", newFilename);
                    if (File.Exists(newFilename))
                    {
                        Console.WriteLine("The file was renamed to " + newFilename);
                    }
                }
            }
        }
    }
}

디렉토리 변경
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a new name for this directory:");
            string newDirName = Console.ReadLine();
            if (newDirName != String.Empty)
            {
                Directory.Move("testdir", newDirName);
                if (Directory.Exists(newDirName))
                {
                    Console.WriteLine("The directory was renamed to " + newDirName);
                }
            }
        }
    }
}

디렉토리 생성
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please enter a name for the new directory:");
            string newDirName = Console.ReadLine();
            if (newDirName != String.Empty)
            {
                Directory.CreateDirectory(newDirName);
                if (Directory.Exists(newDirName))
                {
                    Console.WriteLine("The directory was created!");
                }
            }
        }
    }
}

현재 파일 정보 얻기
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo fi = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
            if (fi != null)
                Console.WriteLine(String.Format("Information about file: {0}, {1} bytes, last modified on {2} - Full path: {3}", fi.Name, fi.Length, fi.LastWriteTime, fi.FullName));
        }
    }
}

디렉토리의 파일 정보 얻기
using System;
using System.IO;

namespace FileHandlingArticleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
            if (di != null)
            {
                FileInfo[] subFiles = di.GetFiles();
                if (subFiles.Length > 0)
                {
                    Console.WriteLine("Files:");
                    foreach (FileInfo subFile in subFiles)
                    {
                        Console.WriteLine("\t" + subFile.Name + "\t(" + subFile.Length + " bytes)");
                    }
                }
            }
        }
    }
}

멤버 변수와 정적 멤버 변수
using System;

class Demo
{
    public static int k;
    public int i;
    public void show()
    {
        Console.WriteLine("k = {0} i = {1}", k, i);
    }
}

class Test
{
    public static void Main()
    {
        Demo a = new Demo();
        a.i = 1;

        Demo b = new Demo();
        b.i = 2;

        Demo.k = 4;

        a.show();
        b.show();
    }
}

ref 타입
using System;

public class Swap
{
    public void swap(ref int x, ref int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }
}

public class Test
{
    static void Main()
    {
        int a = 2;
        int b = 4;

        Swap hi = new Swap();
        hi.swap(ref a, ref b);
        Console.WriteLine("a = {0}, b = {1}", a, b);
    }
}

상속
using System;

class Demo
{
    public class animal
    {
        int weight;
        string name;
        public void show()
        {
            Console.WriteLine("{0} has weight {1}", name, weight);
        }
        public void my_set(int k, string z)
        {
            weight = k;
            name = z;
        }
    }

    public class tiger : animal
    {
        public tiger()
        {
            my_set(100, "tiger");
            show();
        }
    }

    public class lion : animal
    {
        public lion()
        {
            my_set(200, "lion");
            show();
        }
    }

    public static void Main()
    {
        tiger Mike = new tiger();
        lion Bob = new lion();
    }
}

레퍼런스 - 안바뀌는 것
using System;

class Demo
{
    public class Test
    {
        public void change(int k)
        {
            k = k + 2;
        }
    }
    public static void Main()
    {
        int i = 3;
        Test hi = new Test();
        Console.WriteLine("Before {0}", i);
        hi.change(i);
        Console.WriteLine("After {0}", i);
    }
}

레퍼런스 - 리턴받는 것
using System;

class Demo
{
    public class Test
    {
        public int change(int k)
        {
            return k + 2;
        }
    }

    public static void Main()
    {
        int i = 3;
        Test hi = new Test();
        Console.WriteLine("Before {0}", i);
        Console.WriteLine("After {0}", hi.change(i));
    }
}

레퍼런스 - ref 사용한 것
using System;

class Demo
{
    public class Test
    {
        public void change(ref int k)
        {
            k = k + 2;
        }
    }

    public static void Main()
    {
        int i = 3;
        Test hi = new Test();
        Console.WriteLine("Before {0}", i);
        hi.change(ref i);
        Console.WriteLine("After {0}", i);
    }
}

윈도우 폼 생성
using System.Windows.Forms;

class test : Form
{
    public static void Main()
    {
        test Helloform = new test();
        Helloform.Text = "How do you do?";
        Application.Run(Helloform);
    }
}

윈도우 폼 텍스트박스 추가
using System.Windows.Forms;

class test : Form
{
    public static void Main()
    {
        test HelloForm = new test();
        System.Windows.Forms.TextBox text = new System.Windows.Forms.TextBox();

        text.Text = "This is a textbox";
        HelloForm.Controls.Add(text);
        Application.Run(HelloForm);
    }
}

윈도우 폼 체크박스 추가
using System.Windows.Forms;

class test : Form
{
    public static void Main()
    {
        test HelloForm = new test();
        HelloForm.BackColor = System.Drawing.Color.Yellow;

        System.Windows.Forms.CheckBox check = new System.Windows.Forms.CheckBox();
        check.Text = "checkbox";

        HelloForm.Controls.Add(check);
        Application.Run(HelloForm);
    }
}





































'C#' 카테고리의 다른 글

[GUI] Empty Form  (0) 2010.09.19
And

c++ 오버라이딩

|
자식 클래스가 부모 클래스의 오버로드된 함수들 중 하나만 오버라이딩 하면 에러.
모든 함수를 오버라이딩하면 성공.

상속과 무관...
디폴트 생성자 없이 생성자를 만든 후, 그 생성자를 호출하면 에러.
디폴트 생성자 만들고 다른 생성자 만든 후, 그 생성자를 호출하면 성공.

'C++' 카테고리의 다른 글

C++ 생성자  (0) 2010.08.13
생성자와 소멸자  (0) 2010.08.13
동적 할당 0614  (0) 2010.06.14
c++ 0610  (0) 2010.06.10
c++0608  (0) 2010.06.08
And

itoa 대신 sprintf

|
char* itoa(n)
{
static char buf[20];
sprintf(buf, "%s", n);
return buf;
}

char* buf[20]; 하면 리턴된 후 buf는 사라지므로 에러

static char* buf[20];
대신 동적 할당을 사용하면??

while(n) 100 10 1  0
{
cnt++;     1    2  3
n /= 10;  10   1 0
}
char* buf = (char*)malloc(sizeof(char)*cnt);

'C' 카테고리의 다른 글

volatile  (0) 2010.06.26
포인터 상수  (0) 2010.06.24
문자열  (0) 2010.06.13
구조체  (0) 2010.06.12
버블 정렬 c 0609  (0) 2010.06.09
And

라이브러리

|

입력을 받는 함수 3개( scanf(), getch(), gets() ),
출력을 하는 함수 3개( printf(), putch(), puts() )를 만들었다.
또한 수학 관련 함수 5개를 만들었다.
그리고 네트워크 관련 함수 4개도 만들었다.
이것을 각각 컴파일하여 15개의 오브젝트 파일을 만들어 놓았다.
그리고 헤더 파일도 15개 만들어 놓았다.

이제 main() 함수에서 #include로 필요한 함수의 헤더 파일을 포함시켜주고 그 함수를 사용하면 된다.
그리고 컴파일할 때 main() 함수에서 사용한 함수들의 오브젝트 파일을 포함시켜 컴파일해 주면 된다.
그런데 사용한 함수가 15개라면 아래와 같이 해야 할 것이다.
$ gcc -o main.c scanf.o getch.o gets.o printf.o putch.o puts.o ...
쓸 만하다. 
하지만 사용한 함수가 100개라면 어떻게 할 것인가?

그래서 라이브러리 개념을 도입한다.
잘 아는 단어이다. '도서관'이라는 뜻인데 이것이 컴파일과 무슨 관련이 있다는 것인가?
도서관에는 많은 책들이 있다. 그런데 이 많은 책들이 마구 섞여 있지 않고 잘 분류되어 있다는 것이다.
주제에 맞게 책을 분류하고 분류기호를 정해 놓았기 때문에 이 기호를 보고 원하는 책을 빨리 찾을 수 있다.

자, 다시 컴파일로 돌아오자.
15개의 함수를 입출력, 수학, 네트워크 이렇게 3개로 분류하면 좋을 것 같다.
그리고 각각을 libio, libmath, libnet라고 이름을 붙이자. (반드시 앞에 lib를 붙여주어야 함)
그래서 scanf() 함수를 찾으려면 libio를 찾아가면 되는 것이다.

이제 직접 라이브러리를 만들어보자.
GCC에서는 ar이라는 명령어로 라이브러리를 만들 수 있다.
우리는 3개로 분류하였으므로
libio.a
libmath.a
libnet.a
라는 3개의 파일이 만들어진다.
libio.a는 6개의 입출력 오브젝트 파일을 포함하고 있다.
나머지 파일도 해당 오브젝트 파일을 포함하고 있다.

이제 이 라이브러리 파일을 이용해서 컴파일을 하면 된다.
$ gcc -o main main.c -lio lmath lnet -L.
-l 뒤에 lib와 .a를 뺀 io, math, net를 써주면 된다.
-L 뒤에 라이브러리 파일이 포함된 경로를 포함시켜 준다. main.c와 같은 경로라면 .만 찍어 준다.



$ vi input.c
#include <stdio.h>

int input()
{
int in;
printf("What is your favorite number: ");
scanf("%d", &in);
return in;
}
:wq

$ vi output.c
#include <stdio.h>

void output(int out)
{
printf("Your favorite number is %d.\n", out);
}
:wq

$ vi main.c
#include <stdio.h>

int main()
{
int num;
num = input();
output(num);
return 0;
}
:wq

$ vi input.h
extern int input();
:wq

$vi output.h
extern void output(int)
:wq

$ ls
input.c  input.h  main.c  output.c  output.h
$ gcc -c input.c output.c
$ ls
input.c  input.h  input.o  main.c  output.c  output.h  output.o

$ ar r libmylib.a input.o output.o
ar: creating libmylib.a
$ ls
input.c  input.h  input.o  libmylib.a  main.c  output.c  output.h  output.o

$ ar s libmylib.a
$ ls
input.c  input.h  input.o  libmylib.a  main.c  output.c  output.h  output.o

$ ar t libmylib.a
input.o
output.o
$ ls
input.c  input.h  input.o  libmylib.a  main.c  output.c  output.h  output.o

$ gcc -o main main.c -lmylib -L.
$ ls
input.c  input.h  input.o  libmylib.a  main  main.c  output.c  output.h  output.o

$ ./main
What is your favorite number: 3
Your favorite number is 3.






'Compile 강좌' 카테고리의 다른 글

[컴파일 강좌] 2강 - C++ 분할 컴파일  (0) 2010.06.22
[컴파일 강좌] 1강 - C 분할 컴파일  (0) 2010.06.21
컴파일러 옵션  (0) 2010.05.30
And

volatile

|
C complier는 프로그래머가 작성한 소스코드를 최척화하여 컴파일한다.
int a;
a = 10;
a = 20;
a = 30;
이라고 작성하면 C Compiler는 가운데 2줄은 쓸데없는 것으로 인식하고 바로 a에 30의 값을 넣어버린다.

이를 Memory-mapped IO라고 해보자.

#define PORTF (*(unsigned char *)0x62) 
PORTF가 자주 쓰이므로 컴파일러는 0x62가 가리키는 메모리에 직접 값을 쓰거나 읽는 대신 cpu의 레지스터 하나에 값을 쓰거나 읽도록 최적화해버립니다.
그러면 여덟개의 스위치를 무작위로 누르면서 PINC에 값을 변화시키면 이 값은 실제 메모리인 0x62에 쓰여지지 않고 cpu의 레지스터에만 써버리기 때문에 PORTF에는 값이 쓰여지지 않게 된다. 그래서 스위치를 눌러도 LED에 불이 들어오지 않는다.

이를 막기 위해 volatile 키워드를 쓴다.
#define PORTF (*(volatile unsigned char *)0x62) 
이렇게 해주면 컴파일러는 최적화를 하지 않는다. 항상 0x62가 가리키는 메모리에 값을 쓰거나 읽는다.
따라서 스위치를 누를때마다 그 값이 실제 메모리 상에 쓰여지게 되므로 LED에 불이 들어온다.

while(1)
{
PORTF = PINC;
}

'C' 카테고리의 다른 글

itoa 대신 sprintf  (0) 2010.06.26
포인터 상수  (0) 2010.06.24
문자열  (0) 2010.06.13
구조체  (0) 2010.06.12
버블 정렬 c 0609  (0) 2010.06.09
And

포인터 상수

|






#include <stdio.h>


int main(void) {

int arr[4] = {1, 2, 3, 4};


printf("&arr = %p\n", &arr);    // 0012FF54

printf("arr = %p\n", arr);       // 0012FF54

printf("&arr[0] = %p\n", &arr[0]);    // 0012FF54


return 0;

}


arr과 &arr 이 출력하는 메모리주소는 분명 같습니다만,


그 의미에는 미묘한 차이가 있습니다.


익히 아시고 계신 것처럼 arr은 &arr[0] 과 같은 의미이며, 그 data type은 배열의 data type입니다.


즉 arr + 1의 의미는 arr[0]에서 int형의 size만큼, 4byte 이동한 주소, &arr[1]을 의미할 수 있습니다


하지만 &arr은 그렇지 않습니다. &arr은 arr이라는 이름의 int형 4개짜리 일차원 배열의 시작주소입니다.


이것은 즉 (&arr) + 1 이 &arr[1] 을 의미하지 않음을 말합니다.


이러한 맥락에서 (&arr) + 1은 arr[0]에서 int형의 size*배열의 데이터 갯수(4) 를 곱한만큼 이동한 곳


의 주소입니다. 다음의 코드를 봐주세요.


int a[4] = {0, 1, 2, 3};


int (*pa)[4] = &a; /* 그냥 a를 쓰면 에러가 납니다 &a[0]과 &a는 의미하는 바가 달라서입니다


pa는 int형의 데이터 4개를 가지는 일차원배열을 가리키는 포인터입니다 */

pa++; /* 메모리 주소가 sizeof(int) * 4(배열데이터갯수) 만큼 이동합니다 */

printf("%d\n", (*pa)[-1]); /* pa가 가리키는 일차원 배열을 참조한 후 -1 인덱스,

즉 이는 a[3]을 의미합니다 */


출력되는 값은 물론 3입니다 :)


PS) int (*pa)[4]; /* 위에 나온대로 일차원배열을 가리키는 포인터를 선언합니다 */

int *pa[4]; /* int형의 포인터 4개를 가지는 일차원배열을 선언합니다 */











'C' 카테고리의 다른 글

itoa 대신 sprintf  (0) 2010.06.26
volatile  (0) 2010.06.26
문자열  (0) 2010.06.13
구조체  (0) 2010.06.12
버블 정렬 c 0609  (0) 2010.06.09
And

[컴파일 강좌] 2강 - C++ 분할 컴파일

|
클래스 헤더 파일
Point.h
클래스 구현 파일
Point.cpp
메인 함수 파일
main.cpp

클래스 구현 파일을 반드시 클래스 헤더 파일을 포함해야 한다.

클래스 헤더 파일에서 cout을 사용하였다면 반드시
#include <iostream>
using namespace std;
를 써 주어야 한다.

클래스 구현 파일에서 cout을 사용하였다면 반드시
#include <iostream>
using namespace std;
를 써 주어야 한다.

메인 함수 파일에서 cout을 사용하였다면 반드시
#include <iostream>
using namespace std;
를 써 주어야 한다.

클래스 헤더 파일과 구현 파일, 메인 함수 파일 모두에서 cout을 사용하였다면 클래스 헤더 파일에만
#include <iostream>
using namespace std;
를 써 주면 된다.
왜냐하면 클래스 구현 파일과 메인 함수 파일이 클래스 헤더 파일을 #include하고 있기 때문이다.

1) 오브젝트 파일 생성 (컴파일 - 어셈블리)
cl /c main.cpp Point.cpp
main.cpp와 Point.cpp 파일을 각각 컴파일한다. 즉,
cl /c main.cpp의 결과로 main.obj 생성
cl / Point.cpp의 결과로 Point.obj 생성

2) 실행 파일 생성 (링크)
cl main.obj Point.obj
이번에는 두 개의 obj 파일을 합쳐 하나의 실행 파일로 만든다.
제일 앞에 있는 obj 파일의 이름이 실행 파일의 이름이 된다.
따라서 main.exe 파일이 생성된다.

cl Point.obj main.obj
제일 앞에 있는 obj 파일의 이름이 실행 파일의 이름이 된다.
따라서 Point.exe 파일이 생성된다.

'-o test'을 쓰면 main.exe와 test.exe 2개의 실행 파일이 생성된다.








'Compile 강좌' 카테고리의 다른 글

라이브러리  (0) 2010.06.26
[컴파일 강좌] 1강 - C 분할 컴파일  (0) 2010.06.21
컴파일러 옵션  (0) 2010.05.30
And

[컴파일 강좌] 1강 - C 분할 컴파일

|
컴파일 강좌
1강 - C 분할 컴파일
2강 - C++ 분할 컴파일
3강 - 정적 라이브러리
4강 - 동적 라이브러리

하나의 파일에 모든 소스 코드를 넣으면 그 파일의 크기는 얼마나 될까? 그리고 여러 사람이 동시에 작업하는 것이 가능할까?
몇 백명이 투입되는 대형 프로젝트의 경우 모든 작업이 분업화되어 작은 부분을 하나하나 합쳐서 커다란 하나의 프로그램을 만든다.

그러면 각각의 파일을 컴파일하여 오브젝트 파일을 생성하고 이 오브젝트 파일을 하나로 합치는 방법에 대해서 알아보자.

예제1) main.c 파일에 모든 함수를 작성한 경우

main1.c
#include <stdio.h>

void swap(int* a, int* b)
{
    int temp;

    temp = *a;
    *a = *b;
    *b = temp;
}

void disp(int a, int b)
{
    printf("a = %d, b = %d\n", a, b);
}

int main()
{
    int a = 10;
    int b = 30;

    disp(a, b);

    swap(&a, &b);

    disp(a, b);

    return 0;
}
$ gcc -o main1 main1.c


예제2) 3개의 파일로 분할한 경우

swap.c
void swap(int* a, int* b)
{
    int temp;

    temp = *a;
    *a = *b;
    *b = temp;
}

disp.c
void disp(int a, int b)
{
    printf("a = %d, b = %d\n", a, b);
}

main2.c
#include <stdio.h>
#include "swap.c"
#include "disp.c"

int main()
{
    int a = 10;
    int b = 30;

    disp(a, b);

    swap(&a, &b);

    disp(a, b);

    return 0;
}
$ gcc -o main2 main2.c

main2.c는 #include문에 의해 swap.c의 소스와 disp.c의 소스가 그대로 옮겨지기 때문에 전처리가 완료된 후의 소스코드는 main1.c와 같아진다.
소스파일만 분할되어 있고 main2.c만 컴파일한 것이므로 분할 컴파일이라 할 수 없다.


예제3) 3개의 파일을 각각 컴파일하여 오브젝트 파일을 생성한 후, 하나의 실행파일을 만드는 경우

swap.c
void swap(int* a, int* b)
{
    int temp;

    temp = *a;
    *a = *b;
    *b = temp;
}
$ gcc -c swap.c

disp.c
#include <stdio.h>

void disp(int a, int b)
{
    printf("a = %d, b = %d\n", a, b);
}
$ gcc -c disp.c

main3.c
void swap(int*, int*);
void disp(int, int);

int main()
{
    int a = 10;
    int b = 30;

    disp(a, b);

    swap(&a, &b);

    disp(a, b);

    return 0;
}
$ gcc -c main3 main3.c

main() 함수에 있던 #include문이 다 없어졌다.
일단 아래의 두 줄은 각각의 파일을 따로 컴파일하였으므로 당연히 필요가 없다.
대신 main() 함수 안에서 쓰이는 두 함수의 원형을 선언해 주었다.

다음으로 #include <stdio.h>에 대해 살펴 보자.
main1.c나 main2.c에서는 disp() 함수에서 printf() 함수가 쓰이고 있다.
그래서 #include <stdio.h>를 써주었으나 이번에는 각각의 파일을 따로 컴파일하는 것이므로 printf() 함수가 쓰이고 있는 disp.c에 #include <stdio.h>를 써주어야 한다.
그리고 main3.c에서는 #include <stdio.h>를 지웠다.

각각의 파일을 컴파일하면 3개의 오브젝트 파일이 생성된다.
그러면 최종적으로 3개의 파일을 합쳐 보자.
$ gcc -o main3 swap.o disp.o main3.o


하나의 프로그램을 만드는데 100명이 투입되었다고 해 보자.
1명당 함수를 10개씩 만들어야 한다.
그러면 main.c 파일에 선언되어야 하는 함수의 원형은 몇 개일까? 1000개이다.
main.c를 만드는 사람은 1000개의 함수 원형을 선언해야 한다.
그런데 #include문을 생각해 보자.
#include문은 해당 파일의 내용을 그대로 붙여 넣어 준다.
그러면 각각의 개발자가 자신이 만든 함수의 원형 10개만 따로 파일로 작성해서 main.c를 만드는 사람에게 넘겨주면 되는 것 아니겠는가?
main.c를 만드는 사람은 100개의 파일을 받아서 그 파일들만 #include문으로 추가해 주면 된다.
그러면 나머지 900라인을 쓸 필요가 없어지는 것이다. 이 파일이 바로 .h로 끝나는 헤더파일이다.
물론 헤더 파일이 필요한 이유가 이것 때문만은 아니다.

예제4) 헤더 파일을 활용하여 각각의 파일을 컴파일하는 경우

swap.c와 disp.c는 예제3과 동일하다.

swap.h
void swap(int* a, int* b);

disp.h
void disp(int a, int b);

main4.c
#include "swap.h"
#include "disp.h"

int main()
{
    int a = 10;
    int b = 30;

    disp(a, b);

    swap(&a, &b);

    disp(a, b);

    return 0;
}

swap.h와 disp.h에서 각각의 함수의 원형을 선언해 주고, main4.c에서 선언되어 있던 함수의 원형을 지우고 두 개의 헤더파일을 포함시켰다.
결국 전처리가 끝나면 main3.c와 같아진다.
하지만 각각의 헤더 파일에 함수가 10개씩 들어 있다면 main3.c의 경우는 20줄을 적어야 했으나 main4.c는 2줄만 적어주면 된다.

'Compile 강좌' 카테고리의 다른 글

라이브러리  (0) 2010.06.26
[컴파일 강좌] 2강 - C++ 분할 컴파일  (0) 2010.06.22
컴파일러 옵션  (0) 2010.05.30
And

__attribute__

|



The '__attribute__ ( ( signal ) )' directive on the function prototype informs the compiler that the function is an ISR and results in two important changes in the compiler output.
  1. The 'signal' attribute ensures that every processor register that gets modified during the ISR is restored to its original value when the ISR exits. This is required as the compiler cannot make any assumptions as to when the interrupt will execute, and therefore cannot optimize which processor registers require saving and which don't.
  2. The 'signal' attribute also forces a 'return from interrupt' instruction (RETI) to be used in place of the 'return' instruction (RET) that would otherwise be used. The AVR microcontroller disables interrupts upon entering an ISR and the RETI instruction is required to re-enable them on exiting.



Avr-gcc defines an interrupt vector as a name that the linker will use to overide the weak reset addresses in the AVR interrupt vector table. For example, the USART0 receiver interrupt on an ATmega128 is defined as:

#define USART0_RX_vect       _VECTOR(18)

The _VECTOR(18) macro is expanded to:

#define USART0_RX_vect     __vector_18

and so the ISR macro used to define the corresponding interrupt handler in code expands to:

void __vector_18(void) __attribute__ ((signal, __INTR_ATTRS));

and this wll compile into the assembler output as the two lines:

.global  __vector_18
__vector_18:

The linker picks up the name as matching the corresponding interrupt vector table entry and makes the replacement into the vector table. Thus an interrupt with this number will arrive at the corresponding interrupt handler.

However in C++ the name is mangled early in the compile process and prevents the linking from occurring. Patch #6805 allows an interrupt handler name to be represented by a number, and while the name will be mangled as usual, the number survives for later linking. The patch provides for an optional numeric argument to the signal function. An interrupt function prototype using this system for the same USART0 receiver interrupt looks like:

void IntName(void) __attribute__ ((signal(18), __INTR_ATTRS)); 

The numeric signal argument is translated by this Patch into the same two assembler lines as above. The given name is still processed according to the language rules. The name is thus independent of the vector number, but the number is attached to the name. Note that for C++, by the time the signal argument is being processed the given name is mangled.

Once implemented the Patch can be used, but to be versatile it will require an additional definition for each interrupt in each processor. The current proposal is to add the new definition along with those existing. For example, the USART interrupt above for the '128 in file iom128.h will now have two lines.

#define USART0_RX_vect         _VECTOR(18)
#define USART0_RX_vect_num     18

The corresponding new interrupt macro for C++ interrupt declarations is defined in Interrupts.h as:

#define ISRN(name, number) void name(void) __attribute__ ((signal(number), __INTR_ATTRS));







And

동적 할당 0614

|
C++

2차원 배열 동적 할당

int * ptr = new int; == int * ptr = new int [1];

*ptr == ptr[0] == *(ptr + 0)
ptr == &ptr[0] == &*(ptr + 0) == (ptr + 0)

int arr[2][3] = {1, 2, 3, 4, 5, 6};
2차원 배열이지만 실제 메모리 상에서는 1차원 배열이 연속적으로 나열되어 있다.
즉, 3칸짜리 배열 2개가 이어져 있는 경우이다.

머릿속 그림)
┏━┯━┯━┓
┃1│2│3┃
┣━┿━┿━┫
┃4│5│ 6┃
┗━┷━┷━┛

┏━┯━┯━┳━┯━┯━┓
┃1│2│3┃4│5│6┃
┗━┷━┷━┻━┷━┷━┛

실제 메모리)
┏━┯━┯━┳━┯━┯━┓
┃ 1│ 2│ 3┃ 4│ 5│ 6┃
┗━┷━┷━┻━┷━┷━┛

│1│2│3│4│5│6


┌─┬─┬─┬─┬─┬─┐
│1│2│3│4│5│6│
└─┴─┴─┴─┴─┴─┘


arr[0]과 arr[1]은 3칸짜리 배열의 이름이며, 시작주소가 된다.
따라서 타입은 int*가 된다.



arr은 3칸짜리 배열묶음이 2칸인 배열의 이름이며, 시작주소가 된다.
따라서 타입은 int(*)[3]이 된다.






int * ptr = new int[3];
int * * dptr = new int[3];


'C++' 카테고리의 다른 글

C++ 생성자  (0) 2010.08.13
생성자와 소멸자  (0) 2010.08.13
c++ 오버라이딩  (0) 2010.07.03
c++ 0610  (0) 2010.06.10
c++0608  (0) 2010.06.08
And

문자열

|
#문자열
1) 문자 : 끝에 NULL('\0') 문자가 없다.
2) 문자 배열 : 끝에 NULL('\0') 문자가 없다.
2) 문자열 : 문자 배열이면서 끝에 NULL('\0') 문자가 있다.



#문자열 상수
printf("%p\n", 1)
printf("%p\n", '1')
printf("%p\n", "1")
모두 상수이므로 코드 영역에 할당된다.

1) 문자 상수 : 작은 따옴표(')를 이용하여 표시
ex) 'a', '3', '%', '+'
2) 문자열 상수 : 큰 따옴표(")를 이용하여 표시
ex) "This is a string."

#상수 테이블
1) 심볼 테이블 : 프로그램 내의 모든 변수의 정보가 기록되어 있다.
2) 상수 테이블 : 프로그램 내의 모든 상수의 정보가 기록되어 있다.
문자열 "string"
%d로 출력 -> "string"의 시작주소
%p로 출력 -> "string"

#문자열 선언
char carray[] = {'a', 'b', 'c'};
연속된 3개의 공간에 문자 'a', 'b', 'c'가 값으로 들어가 있는 문자 배열이다.
char string1[] = {'a', 'b', 'c', '\0'};
연속된 4개의 공간에 문자 'a', 'b', 'c'와 NULL('\0') 문자가 들어가 있는 문자열이다.
각각의 문자가 코드 영역에 순서대로 할당되고, 'a'의 시작주소가 string1에 대입된다.
메모리 할당은 코드 영역에 될까? 스택 영역에 될까?
char string2[] = "abc";
"abc"는 코드 영역에 'a', 'b', 'c', '\0'으로 할당되어 있고, 스택 영역에 배열로 할당된다???
string2에는 다른 값을 대입할 수 없다. 주소이기 때문이다. 각각의 문자변수([0], [1], [2], [3])에 값을 넣어야 바꿀 수 있다.
char *string3 = "abc";
"abc"는 코드 영역에 'a', 'b', 'c', '\0'으로 할당되어 있고, 스택 영역에 할당된 string3에 "abc"의 시작 주소가 들어가 있다.
string3에는 다른 값을 대입할 수 있다. 포인터 변수이기 때문이다.

#잘못된 문자열 선언
char string[3] = "abc";


#gets()
원형 : char *gets(char *str);
읽은 문자열을 가리키는 포인터를 반환하며, 오류가 발생하면 NULL을 반환한다.
개행문자가 나올 때까지 읽어서, 개행문자 이전까지의 문자열에 NULL 문자를 붙인 문자열을 만든 후, 매개변수가 가리키는 메모리 공간에 저장하고, 그 시작 주소를 반환한다.
1)scanf() : 단어 입력
2)gets() : 문장 입력

#puts()
원형 : int puts(char *str)
매개변수가 가리키는 값을 출력하고 마지막에 개행문자를 자동으로 출력한다.
정상적으로 실행한 후 마지막 출력문자를 반환한다. 대부분의 경우 '\n'을 출력한다.
오류가 발생하면 EOF를 반환한다.

#포인터 변수의 초기화
포인터 변수를 초기화하지 않으면 경고 메시지를 보여준다.

#문자열 함수
1) int strlen(char *s)
2) int strcmp(char *s1, char *s2)
3) int strncmp(char *s1, char *s2, int n)
4) char *strcpy(char *s1, char *s2)
5) char *strncpy(char *s1, char *s2, int n)
6) char *strcat(char *s1, char *s2)
7) char *strchr(const char *string, int c)
8) char *strrchr(const char *string, int c)
9) int atoi(const char *s)
10)int itoa(int value, char *string, int radix)


#문자열 배열
char strings[N][M] = {"string1", "string2", "string3", ... "stringN" };
최대 M의 길이를 가지는 문자열 N개를 작성할 수 있다.
코드 영역에 N개의 문자열 공간이 할당되고, 스택에도 N*M만큼의 공간이 할당된다.

#문자열 포인터 배열
char *strings[N] = {"string1", "string2", "string3", ... "stringN" };
길이 제한 없는 문자열 N개를 작성할 수 있다.
코드 영역에 N개의 문자열 공간이 할당되고, 스택에는 그 문자열의 시작주소를 가리키는 4*N만큼의 공간이 할당된다.
메모리 공간이 절약되고 문자열을 편리하게 다룰 수 있다.

원본 문자열 배열의 시작 주소만 가지는 포인터 배열은 원본의 변경없이 포인터만 바꿔주면 정렬 등의 기능을 수행할 수 있다.


#main() 함수
int main(int argc, char *argv[]);
argc, argv는 관례적으로 사용하는 것이며, 사용자가 바꿀 수 있다.
공백을 포함한 문자열을 큰따옴표로 묶으면 하나의 인수로 인식한다.

#문자 함수
1) int isalnum(int c)
2) int isalpha(int c)
3) int iscntrl(int c)
4) int isdigit(int c)
5) int isgraph(int c)
6) int islower(int c)
7) int is print(int c)
8) int ispunct(int c)
9) int isspace(int c)
10) int isupper(int c)
11) int isxdigit(int c)
12) tolower(int ch)
13) toupper(int ch)






#문자열

char string = "test";

string = string+0 = &string[0]
*string = *(string+0) = string[0]
string + 1 = &string[1]
*(string + 1) = *&string[1] = string[1]
*(1+string) = *&1[string] = 1[string]
printf("%p\n", "abc");


배열크기는 변수로 지정할 수 없다??? 디파인된 상수로는 가능??






'C' 카테고리의 다른 글

volatile  (0) 2010.06.26
포인터 상수  (0) 2010.06.24
구조체  (0) 2010.06.12
버블 정렬 c 0609  (0) 2010.06.09
다중포인터  (0) 2010.06.08
And
prev | 1 | 2 | 3 | next