string processing

|
#include <stdio.h>

#define TRUE    1
#define FALSE   0

void disp(char ch, int (*fp)(char)) {
        if (fp(ch)) printf("TRUE\n");
        else printf("FALSE\n");
}

int myisalnum(char ch) {
        if ((ch >= 'a' && ch <= 'z') ||
                        (ch >= 'A' && ch <= 'Z') ||
                        (ch >= '0' && ch <= '9')) {
                return TRUE;
        } else {
                return FALSE;
        }
}

int mystrlen(const char* str)
{
        int i;
        for (i = 0; str[i] != '\0'; ++i);

        return i;
}

int mystrcpy(char* buf, const char* str)
{
        int i;
        for (i = 0; str[i] != '\0'; ++i) {
                buf[i] = str[i];
        }
        buf[i] = '\0';

        return i;
}

int mystrcat(char *buf, const char* str)
{
        int i;
        int j;
        for (i = 0; buf[i] != '\0'; ++i); //최종적으로 i는 '\0'의 위치에 있음 (buf[i] == '\0')
        for (j = 0; str[j] != '\0'; ++i, ++j) {
                buf[i] = str[j];
        }
        buf[i] = '\0';

        return j;
}

int mystrrev(char *str)
{
        int i;
        int len;
        char temp;

        for (i = 0; str[i] != '\0'; ++i); //i는 문자열의 길이가 됨
        len = i;
        //printf("%d\n", len);

        for (i = 0; i < len / 2; ++i) {
                temp = str[i];
                str[i] = str[len - i - 1];
                str[len - i - 1] = temp;
        }
        str[len] = '\0';

        //debug start
        printf("mystrrev debug : ");
        for (i = 0; str[i] != '\0'; ++i) {
                printf("%c", str[i]);
        }

        if (str[i] == '\0') printf("NULL\n");
        //debuf end

        return i;
}

int mystrcmp(char *str1, char *str2)
{
        int i;
        int len1, len2;
        int len;

        for (i = 0; str1[i] != 0; ++i);
        len1 = i;

        for (i = 0; str2[i] != 0; ++i);
        len2 = i;

        //긴 문자열의 길이를 구한다.
        len = (len1 > len2) ? len1 : len2;

        for (i = 0; i < len; ++i) {
                //같은 위치의 문자를 비교한다.
                if (str1[i] > str2[i]) {
                        return 1;
                } else if (str1[i] < str2[i]) {
                        return -1;
                }

                //둘 중 하나가 '\0'이 되면 앞의 문자들이 모두 같다는 것이다.
                if (str2[i] == '\0') {
                        return 1;
                } else if (str1[i] == '\0') {
                        return -1;
                }
        }

        return 0;
}

int main()
{
        int i;
        int (*fp[2])(char);

        char *str;
        char dest[10];
        char rstr[] = "abcdef";

        fp[0] = myisalnum;
        fp[1] = myisalnum;
        for (i = 0; i < 2; ++i) {
                disp('/', fp[i]);
        }

        str = "abc";
        i = mystrlen(str); //3
        printf("mystrlen : [%s] %d\n", str, i);
        i = mystrlen("\0"); //0
        printf("mystrlen : [%s] %d\n", str, i);

        mystrcpy(dest,str);
        printf("mystrcat : dest [%s]\n", dest);

        str = "def";
        mystrcat(dest, str);
        printf("mystrcat : dest [%s]\n", dest);

        mystrrev(rstr);
        printf("mystrrev : %s\n", rstr);

        i = mystrcmp("abc", "abc");
        printf("mystrcmp : %d\n", i);

        return 0;
}

And

연슴장 스캔본

|
-

012


-

012


-
And

[Ruby] Regex \0, \1, \2, ...

|
-
\0 : 마지막으로 일치한 부분
\1 : 마지막으로 일치한 전체 문자열 중 첫번째 그룹
\2 : 마지막으로 일치한 전체 문자열 중 두번째 그룹
...

"replacing in regex".gsub /\sin\s/, ' is easy in '
=> "replacing is easy in regex"

"replacing in regex".gsub /\sin\s/, ' is easy\0 '
=> "replacing is easy in regex"

문자열의 첫번째 문자부터 비교하면서 새로운 배열에 그 값을 넣는다.
그러면 일치하지 않는 부분은 그대로 새로운 배열에 들어간다.
일치하는 부분이 나오면 해당 부분을 치환하여 새로운 배열에 넣는다.
'\0'이 일치한 문자열 전체이므로 ' in '이 되어 'easy' 뒤에 들어간다.
그리고 남은 부분부터 다시 비교하면서 새로운 배열에 들어간다.

"replacing in regex".gsub /\si(n)\s/, ' is easy i\1 '
=> "replacing is easy in regex"


"AbcDef".gsub(/([a-z])([A-Z])/, '\1_\2').downcase
=> "abc_def"

마지막으로 일치한 부분이 "cD"이다.
첫번째, 두번째 그룹에 속하는 부분이 'c', 'D'이므로 각각 '\1', '\2'에 해당한다.
따라서, "abc_def"가 된다.

-
And

apt-get

|
1장. 리눅스 커널 프로그래밍 환경 구축
5. 데비안 패키지 관리

shell에서 문자 출력이 제대로 되지 않을 경우 언어환경이 한글로 설정되어 있기 때문인데 정상 출력을 위해 다음을 입력
# export LANG=C

apt-get 패키지
# vi /etc/apt/sources.list

deb http://ftp.kr.debian.org/debian/ stable main non-free contrib

stable : 안정판
main : 메인 패키지
non-free : 자유 소프트웨어가 아닌 것들
contrib : 라이선스 소프트웨어에 의존하는 자유 소프트웨어

안정판 : gcc 3.x 버전으로 컴파일 (ANSI C90)
불안정판 : gcc 4.x 버전으로 컴파일 (ANSI C99)

2.6.10 까지 : gcc 3.x 버전으로 컴파일 가능, gcc 4.x 버전으로 컴파일하면 비표준 C 코드들을 오류로 경고
2.6.11 이후 : gcc 4.x 버전으로 컴파일 가능, gcc 3.x 버전으로 컴파일 가능 (gcc 3.3)

6. SSH 환경 설정하기

텔넷은 전송되는 데이터가 그대로 노출되기 때문에 암호화를 통해 전송되는 SSH를 가장 많이 사용

7. bash 환경 설정하기

LANG=C; export LANG; : 언어 설정을 추가해서 메시지 깨짐을 제거

echo -ne '\033[11;0]' : 경고 비프음을 제거

export LS_OPTIONS='--color=auto'
eval "'dircolors'"
alias ls='ls $LS_OPTIONS'
alias ll='ls $LS_OPTIONS -l'
alias l='ls $LS_OPTIONS -lA'

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# source /root/.bashrc : 변경 사항 적용

make modules_install 시 에러
Version requires old depmod, but couldn't run /sbin/depmod.old: No such file or dir
해결책 : cp /sbin/depmod /sbin/depmod.old




'linux' 카테고리의 다른 글

gst  (0) 2010.10.22
SHELL  (0) 2010.08.22
쉘프로그래밍  (0) 2010.06.05
라이브러리 만들기  (0) 2010.05.31
gdb 사용법  (0) 2010.05.31
And

gst

|
gst-plugin-ugly x264 에러 : ./etc/x264ex~.c 585 b_bframe_pyramid --> i_bframe_pyramid


gcc -v 인클루드 패스 볼 수 있음


'linux' 카테고리의 다른 글

apt-get  (0) 2010.10.30
SHELL  (0) 2010.08.22
쉘프로그래밍  (0) 2010.06.05
라이브러리 만들기  (0) 2010.05.31
gdb 사용법  (0) 2010.05.31
And

[lds]

|
설계와 구현을 통한 임베디드 OS의 이해와 응용(1) - Overview

설계와 구현을 통한 임베디드 OS의 이해와 응용(2) - 개발환경 구성 및 부트로더 작성(1)http://www.hanb.co.kr/network/view.html?bi_id=1166
설계와 구현을 통한 임베디드 OS의 이해와 응용(2) - 개발환경 구성 및 부트로더 작성(2)http://www.hanb.co.kr/network/view.html?bi_id=1167
설계와 구현을 통한 임베디드 OS의 이해와 응용(3) - cuteOS의 시작 부분(1)http://www.hanb.co.kr/network/view.html?bi_id=1170
http://clansim.tistory.com/tag/elf32-littlearm lds 상세주석

'AT91SAM7S256' 카테고리의 다른 글

[Lowlevel.c]  (0) 2010.10.04
And

[Lowlevel.c]

|


[1단계 - EFC Init] (내장 플래시 메모리 컨트롤러 초기화)

[소스 코드]

1
2
3
4
5
6
#ifdef AT91SAM7S512 //선택적 컴파일, 전처리지시어
	AT91C_BASE_MC->MC0_FMR = AT91C_MC_FWS_1FWS; // 1 Wait State to work at 48MHz
	AT91C_BASE_MC->MC1_FMR = AT91C_MC_FWS_1FWS; // 1 Wait State to work at 48MHz
#else
	AT91C_BASE_MC->MC_FMR = AT91C_MC_FWS_1FWS; // 1 Wait State to work at 48MHz
#endif

[소스 분석]
Makefile에 TARGET=AT91SAM7S256으로 정의되어 있으므로 else문이 실행된다.
메모리 컨트롤러는 임베디드 플래시 컨트롤러를 포함하고 있고, FMR은 플래시 메모리의 모드를 설정할 수 있는 레지스터이다.
메모리 컨트롤러의 FMR의 FWS (Flash Wait State)를 0x01로 설정한다. (리드 동작 : 2사이클 웨이트, 라이트 동작 : 3사이클 웨이트)
//내용추가

[매크로 분석]
1. AT91C_BASE_MC
#define AT91C_BASE_MC (AT91_CAST(AT91PS_MC)0xFFFF_FF00) // (MC) Base Address

#define AT91C_BASE_MC ((AT91PS_MC)0xFFFF_FF00)

#define AT91C_BASE_MC ((struct _AT91S_MC *)0xFFFF_FF00)

AT91_CAST(AT91PS_MC) --> (AT91PS_MC) (AT91SAM7S256.h 64 line)
AT91PS_MC --> struct _AT91S_MC (AT91SAM7S256.h 720 line)

2. MC_FMR (MC Flash Mode Register)
#define MC_FMR (AT91_CAST(AT91_REG *)0x0000_0060) // (MC_FMR) MC Flash Mode Register

#define MC_FMR (AT91_CAST(volatile unsigned int *)0x0000_0060)

#define MC_FMR ((volatile unsigned int *)0x0000_0060)

AT91_REG --> volatile unsigned int (AT91SAM7S256.h 63 line)
AT91_CAST(volatile unsigned int) --> (volatile unsigned int) (AT91SAM7S256.h 64 line)

3. AT91C_MC_FWS_1FWS
#define AT91C_MC_FWS_1FWS (0x1 << 8) // (MC) 2 cycles for Read, 3 for Write operations

#define AT91C_MC_FWS_1FWS (0x0100)

[매크로 분석 결과]
((struct _AT91S_MC *)0xFFFF_FF00) + ((volatile unsigned int *)0x0000_0060 = (0x0100);



[2단계 - PMC Init - STEP 1] (전력관리 컨트롤러 초기화)

[소스 코드]
1
2
AT91C_BASE_PMC->PMC_MOR = (((AT91C_CKGR_OSCOUNT & (0x40 << 8)) | AT91C_CKGR_MOSCEN));
while (!(AT91C_BASE_PMC->PMC_SR & AT91C_PMC_MOSCS));

[소스 분석]
line 1: 전력관리 컨트롤러의 메인 오실레이터 레지스터를 로 설정한다.
line 2: 메인 오실리에이터가 안정화될 때까지 기다린다. 왜냐하면 클럭 속도가 서서히 올라가기 때문이다.

[매크로 분석]
1단계 분석 방법과 동일

[매크로 분석 결과]
((volatile unsigned int *)0xFFFFFC20) = (0xFF << 8) & (0x40 << 8) | (0x1 << 0) = 0x4000 | 0x01
= 0100_0000_0000_0000 | 0x01
OSCOUNT = 0100_0000 (메인 오실레이터의 스타트업 시간을 8 * 슬로우 클록 주기수로 지정한다.
MOSCEN = 1로 설정하면 동작이 개시된다.


[3단계 - PMC Init - STEP 2] (전력관리 컨트롤러 초기화)

[소스 코드]
1
2
3
4
5
6
7
AT91C_BASE_PMC->PMC_PLLR = AT91C_CKGR_USBDIV_1           |
	AT91C_CKGR_OUT_0              |
	(16 << 8)                     |
	(AT91C_CKGR_MUL & (72 << 16)) |
	(AT91C_CKGR_DIV & 14);
while (!(AT91C_BASE_PMC->PMC_SR & AT91C_PMC_LOCK));
while (!(AT91C_BASE_PMC->PMC_SR & AT91C_PMC_MCKRDY));

[소스 분석]
크리스털의 클럭 주파수는 18.432Hz
 
(p310)
 
이다. 이 값을 DIV로 나눈 값에 ~를 곲하면 96MHz가 나온다.
이 값이 PLL의 클럭 주파수가 된다.

그리고 이 값을 2로 나눈 값인 48MHz가 UDP의 주파수가 된다.
UDP가 필요한 이유는 프로그램을 Write할 때 USB를 사용하기 때문이다.

line 1: CKGR_USBDIV_1 = (0x1 << 28) : (PLL 출력 주파수 / 2)를 사용한다.
line 2 : AT91C_CKGR_OUT_0 = (0x0 <<14) : PLL 출력 주파수가 80~160MHz의 범위에 있다.
line 4 : AT91C_CKGR_MUL (0x7FF << 16) : PLL 회로에 의하여 주파수가 (MUL + 1)배로 곱해진다.
line 5 : AT91C_CKGR_DIV (0xFF << 0) : 메인 클록이 DIV로 나누어져 PLL 회로에 공급된다.
line 6 : PMC_SR의 2번 비트가 1이 될 때까지 기다린다. (PLL이 lock될 때까지 기다린다.)
line 7 : PMC_SR의 8, 9, 10번 비트 중 하나가 1이 될 때까지 기다린다. (마스터 클록이 ready 상태가 될 때까지 기다린다.)

[매크로 분석]
1단계 분석 방법과 동일

[매크로 분석 결과]
((volatile unsigned int *)0xFFFFFC2C) = //내용 추가



-

'AT91SAM7S256' 카테고리의 다른 글

[lds]  (0) 2010.10.05
And

[CustomAdapter]

|
커스텀뷰 xml 작성
<RelativeLayout>
<ImageView />
<TextView />
<Button />
</RelativeLayout>

리스트뷰 listtest.xml 작성
<LinearLayout>
<ListView />
</LinearLayout>

.java 작성
setContentView(R.layout.listtest)

ArrayList 생성
MyItem 생성하여 ArrayList에 추가
ArrayList를 커스텀어댑터에 붙임

CustomAdapter 클래스 정의
BaseAdapter 상속


CustomAdapter 객체 생성
MyListAdapter myAdapter = new MyListAdapter(this, R.layout.icontext, arItem);

ListView 생성
listtest.xml에서 listview를 가져옴
myList.setAdapter(myAdapter);

어댑터뷰에서 데이터를 가져오는 방법
객체에서 : new (this, customview_xml, data_instance)
xml에서 : createFromResource(this, data_xml, view_design)


-

'Android' 카테고리의 다른 글

[MyHandlerTest]  (0) 2010.09.28
[ImageButton, Toast]  (0) 2010.08.23
[AlertDialog2]  (0) 2010.08.19
[AlertDialog]  (0) 2010.08.18
[MenuTest]  (0) 2010.08.18
And

[MyHandlerTest]

|

MyHandlerTest.java
package net.itisn.com;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MyHandlerTest extends Activity {
	TextView increaseText;
	TextView decreaseText;
	Button startButton;
	
	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        increaseText = (TextView)this.findViewById(R.id.increase);
        decreaseText = (TextView)this.findViewById(R.id.decrease);
        startButton = (Button)this.findViewById(R.id.start);
        
        increaseText.setTextSize(30);
        decreaseText.setTextSize(30);
        startButton.setTextSize(30);
        
        startButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				new Thread(new IncreaseThread(updateHandler)).start();
		        new Thread(new DecreaseThread(updateHandler)).start();
			}
		});
    }
	
	class IncreaseThread extends Thread {
		Handler updateHandler;
		int increaseValue = 0;
		
		public IncreaseThread(Handler updateHandler) {
			this.updateHandler = updateHandler;
		}
		
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				increaseValue++;
				Message msg = Message.obtain();
				msg.what = 0;
				msg.arg1 = increaseValue;
				updateHandler.sendMessage(msg);
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	class DecreaseThread extends Thread {
		Handler updateHandler;
		int decreaseValue = 100;
		
		public DecreaseThread(Handler updateHandler) {
			this.updateHandler = updateHandler;
		}
		
		public void run() {
			// TODO Auto-generated method stub
			while (true) {
				decreaseValue--;
				Message msg = Message.obtain();
				msg.what = 1;
				msg.arg1 = decreaseValue;
				updateHandler.sendMessage(msg);
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	Handler updateHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			if (msg.what == 0) {
				increaseText.setText("Increase : " + msg.arg1);
			} else if (msg.what == 1) {
				decreaseText.setText("Decrease : " + msg.arg1);
			}
		}
		
	};
}


-

'Android' 카테고리의 다른 글

[CustomAdapter]  (0) 2010.09.30
[ImageButton, Toast]  (0) 2010.08.23
[AlertDialog2]  (0) 2010.08.19
[AlertDialog]  (0) 2010.08.18
[MenuTest]  (0) 2010.08.18
And

qt 메뉴 등록

|
1. 메뉴바 작성
QMenuBar menuBar = new QMenuBar;
2. 액션 작성
QAction newAction = new QAction(tr("&New"), this);
connect(newAction, SIGNAL(triggered()), this, SLOT(open()));
3. 메뉴를 메뉴바에 추가
fileMenu = menuBar()->addMenu(tr("&File"));
4. 메뉴에 액션 추가
fileMenu->addAction(newAction);


'Qt' 카테고리의 다른 글

[Qt Designer] 확장 다이얼로그  (0) 2010.09.22
Qt Designer  (0) 2010.09.18
Qt Creator Manual  (0) 2010.06.10
Qt Compile  (0) 2010.06.06
And

[Qt Designer] 확장 다이얼로그

|
전체 다이얼로그 작성
More 버튼 (toggle) -> 확장될 위젯들 (setVisible)
cpp의 생성자에서 확장될 위젯들은 hide()
-

'Qt' 카테고리의 다른 글

qt 메뉴 등록  (0) 2010.09.23
Qt Designer  (0) 2010.09.18
Qt Creator Manual  (0) 2010.06.10
Qt Compile  (0) 2010.06.06
And

[GUI] Empty Form

|
-
1. File | new Project
Empty Project 선택, Name 지정 (EmptyForm)
2. Project | Add Reference
.Net 탭에서 System.Windows.Form 선택
3. 코드 작성
EmptyForm.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Windows.Forms;

public class EmptyForm : System.Windows.Forms.Form
{
    public EmptyForm()
    {
    }

    public static int Main()
    {
        Application.Run(new EmptyForm());
        return 0;
    }
}

FirstWindowApplication
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class MyFirstWindow : System.Windows.Forms.Form
{
    public MyFirstWindow()
    {
        initializeComponent();
    }

    private void initializeComponent()
    {
        this.Size = new System.Drawing.Size(300, 300);
        this.Text = "MyFirstWindow";
    }

    public static void Main(string[] args)
    {
        Application.Run(new MyFirstWindow());
    }
}

AFormBasedWindowSkeleton.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System;
using System.Windows.Forms;

class WinSkel : Form
{
    public WinSkel()
    {
        Text = "A Windows Skeleton";
    }

    [STAThread]
    public static void Main()
    {
        WinSkel skel = new WinSkel();
        Application.Run(skel);
    }
}

ExitApplication.cs
using System;
using System.Windows.Forms;
using System.Drawing;

class FormExit : Form
{
    Button StopButton;

    public FormExit()
    {
        Text = "Adding a Stop Button";

        StopButton = new Button();
        StopButton.Text = "Stop";
        StopButton.Location = new Point(100, 100);

        StopButton.Click += StopButtonClick;
        Controls.Add(StopButton);
    }

    [STAThread]
    public static void Main()
    {
        FormExit skel = new FormExit();

        Application.Run(skel);
    }

    protected void StopButtonClick(object who, EventArgs e)
    {
        Application.Exit();
    }
}

ButtonEventHnadler.cs
using System;
using System.Windows.Forms;
using System.Drawing;

public class ButtonClickEvent : System.Windows.Forms.Form
{
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.TextBox textBox1;

    public ButtonClickEvent()
    {
        Text = "Test WinForm";

        ForeColor = System.Drawing.Color.Yellow;

        button1 = new System.Windows.Forms.Button();
        textBox1 = new System.Windows.Forms.TextBox();

        button1.Location = new System.Drawing.Point(8, 32);
        button1.Name = "button1";
        button1.Size = new System.Drawing.Size(104, 32);
        button1.TabIndex = 0;
        button1.Text = "Click Me";

        textBox1.Location = new System.Drawing.Point(24, 104);
        textBox1.Name = "textBox1";
        textBox1.Size = new System.Drawing.Size(184, 20);
        textBox1.TabIndex = 1;
        textBox1.Text = "textBox1";

        Controls.AddRange(new System.Windows.Forms.Control[]{textBox1, button1});
        
        button1.Click += new System.EventHandler(button1_Click);
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        textBox1.Text = "Button is clicked";
        MessageBox.Show("Button is clicked");
    }

    public static int Main()
    {
        Application.Run(new ButtonClickEvent());
        return 0;
    }
}

SeparateMainClass.cs
using System;
using System.Drawing;
using System.Windows.Forms;

class SeparateMain
{
    public static void Main()
    {
        Application.Run(new AnotherHelloWorld());
    }
}

class AnotherHelloWorld : Form
{
    public AnotherHelloWorld()
    {
        Text = "Another HelloWolrd";
        BackColor = Color.White;
    }

    protected override void OnPaint(PaintEventArgs pea)
    {
        Graphics graphics = pea.Graphics;

        graphics.DrawString("Hello, Windows Form!", Font, Brushes.Black, 0, 0);
    }
}

ResumeLayoutAndSuspendLayout.cs 
using System;
using System.Windows.Forms;

class MainForm : Form
{
    private Label label1;
    private TextBox textBox1;
    private Button button1;

    public MainForm()
    {
        this.label1 = new Label();
        this.textBox1 = new TextBox();
        this.button1 = new Button();
        this.SuspendLayout();

        this.label1.Location = new System.Drawing.Point(16, 36);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(128, 16);
        this.label1.TabIndex = 0;
        this.label1.Text = "Please enter your name:";

        this.textBox1.Location = new System.Drawing.Point(152, 32);
        this.textBox1.Name = "textBox1";
        this.textBox1.TabIndex = 1;
        this.textBox1.Text = "";

        this.button1.Location = new System.Drawing.Point(109, 80);
        this.button1.Name = "button1";
        this.button1.TabIndex = 2;
        this.button1.Text = "Enter";
        this.button1.Click += new System.EventHandler(this.button1_Click);

        this.ClientSize = new System.Drawing.Size(292, 126);
        this.Controls.Add(this.button1);
        this.Controls.Add(this.textBox1);
        this.Controls.Add(this.label1);
        this.Name = "form1";
        this.Text = "Visual C#";

        this.ResumeLayout(false);
    }

    private void button1_Click(object sender, System.EventArgs e)
    {
        System.Console.WriteLine("User entered: " + textBox1.Text);
        MessageBox.Show("Welcome, " + textBox1.Text, "Visual C#");
    }

    [STAThread]
    public static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new MainForm());
    }
}

23.2.7
ShowFormAndSleep.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Threading;
using System.Windows.Forms;

class ShowFormAndSleep
{
    public static void Main()
    {
        Form form = new Form();
        form.Show();
        Thread.Sleep(2500);
        form.Text = "My First Form";
        Thread.Sleep(2500);
    }
}

















-

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

C# 기본  (0) 2010.07.26
And

Qt Designer

|
Qt Designer 실행
폼 작성
formname.ui로 저장 (XML 형식)
main.cpp 작성 (ui_formname.h 인클루드)
qmake -project
qmake gotocell.pro -> ui_formname.h (C++ 형식) 생성됨 (fornname.ui --> ui_formname.h : uic가 수행)

formname.h 작성 (ui_formname.h 인클루드, Ui::formname 상속받아야 함)
formname.cpp 작성 (생성자에서 setupUi(this);를 해주어야 함)
main.cpp 수정 (formname.h 인클루드)

-

'Qt' 카테고리의 다른 글

qt 메뉴 등록  (0) 2010.09.23
[Qt Designer] 확장 다이얼로그  (0) 2010.09.22
Qt Creator Manual  (0) 2010.06.10
Qt Compile  (0) 2010.06.06
And

정규식을 이용한 주민등록번호 추출

|
정규식을 이용한 주민등록 번호 추출 프로그램
RRNTest.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//\d\d(0[1-9]|1[0-2])([0-2][1-9]|3[0-1])[1-4]\d{6}

//Regular Expression
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(PatternStr);

	Matcher mat;
	boolean found;
	boolean more = true;

	public String FindRRN(String str) {
		mat = pat.matcher(str);
		found = mat.find();
		if (found)
		{
			rrn = mat.group();
			more = true;
			//end()는 mat.group() 후에 사용 가능
			str = str.substring(mat.end());
		}
		else
		{
			rrn = "Not found";
			more = false;
		}
		return str;
	}
}

public class RRNTest {
	public static void main(String[] args) {
		String str = "8204254093614abc128714cd7903241081511AE@5605047145666#";
		boolean more = true;
		RRN r = new RRN();
		while (r.more) {
			str = r.FindRRN(str);
			if (r.rrn != "Not found") System.out.println(r.rrn);
		}
	}
}


-

'Java' 카테고리의 다른 글

java  (0) 2010.08.31
쓰레드  (0) 2010.08.26
오토박싱/언박싱  (0) 2010.08.24
Stream  (0) 2010.08.23
Exception  (0) 2010.08.23
And

java

|
레이아웃 변경하기
setLayout(new CardLayout());
Container c = getContentPane();
c.setLayout(new GridLayout());

쓰레드
일시 정지 상태로 만드는 것 : suspend, join, sleep, wait
깨우는 것 : resume, notify

'Java' 카테고리의 다른 글

정규식을 이용한 주민등록번호 추출  (0) 2010.09.07
쓰레드  (0) 2010.08.26
오토박싱/언박싱  (0) 2010.08.24
Stream  (0) 2010.08.23
Exception  (0) 2010.08.23
And

쓰레드

|
run() 메소드는 Runnable 인터페이스에 존재
Thread 클래스는 Runnable 인터페이스를 임플러먼츠한다.
따라서 Thread클래스를 사용하여 쓰레드를 사용하려면 run() 메소드를 기술해줘야 하고, start() 메소드로 실행해야 한다. start() 메소드는 run() 메소드를 실행한다. 그냥 run()을 실행하면 멀티쓰레드로 동작하지 않는다.

Runnable 인터페이스를 임플러먼츠한 후,

객체를 생성하여 그 객체를 
Thread t = new Thread(rr, "Thread1"); 에 넘기고
t.start()로 실행하면 start()가 rr의 run()을 실행함

쓰레드 돌릴때 run()에 반드시 sleep(1)이라도 주어야 cpu 부하 줄어들고, 멀티 쓰레드시 효율이 높다

'Java' 카테고리의 다른 글

정규식을 이용한 주민등록번호 추출  (0) 2010.09.07
java  (0) 2010.08.31
오토박싱/언박싱  (0) 2010.08.24
Stream  (0) 2010.08.23
Exception  (0) 2010.08.23
And

오토박싱/언박싱

|
int n = 10;
Integer wrapN = new Integer(n); //박싱

n = wrapN.intValue(); //언박싱

wrapN = n; //오토 박싱
n = wrapN; //오토 언박싱

'Java' 카테고리의 다른 글

java  (0) 2010.08.31
쓰레드  (0) 2010.08.26
Stream  (0) 2010.08.23
Exception  (0) 2010.08.23
자바 주요 클래스  (0) 2010.08.19
And

[ImageButton, Toast]

|

C++pasted just now: 
package net.itisn.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;

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

		ImageButton btn1 = (ImageButton) this.findViewById(R.id.ImageButton01);
		ImageButton btn2 = (ImageButton) this.findViewById(R.id.ImageButton02);
		ImageButton btn3 = (ImageButton) this.findViewById(R.id.ImageButton03);
		ImageButton btn4 = (ImageButton) this.findViewById(R.id.ImageButton04);

		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(FrameLayoutTest.this, "Hi~~ north",
				        Toast.LENGTH_LONG).show();
			}
		});
	}
}


d
Haskellpasted 1 second ago: 
<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
	android:id="@+id/FrameLayout01"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	xmlns:android="http://schemas.android.com/apk/res/android"
>
	<ImageButton
		android:id="@+id/ImageButton01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="top|center"
		android:background="@drawable/su"
	></ImageButton>
	<ImageButton
		android:id="@+id/ImageButton02"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="left|center"
		android:src="@drawable/icon"
	></ImageButton>
	<ImageButton
		android:id="@+id/ImageButton03"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="right|center"
		android:src="@drawable/icon"
	></ImageButton>
	<ImageButton
		android:id="@+id/ImageButton04"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_gravity="bottom|center"
		android:src="@drawable/icon"
	></ImageButton>

</FrameLayout>


-

'Android' 카테고리의 다른 글

[CustomAdapter]  (0) 2010.09.30
[MyHandlerTest]  (0) 2010.09.28
[AlertDialog2]  (0) 2010.08.19
[AlertDialog]  (0) 2010.08.18
[MenuTest]  (0) 2010.08.18
And

용어 tabstop shiftwidth

|
tabstop : '\t' 문자 자체의 화면에서의 표시 간격
indent size(shiftwidth) : > 또는 <, 그리고 자동 인덴트 같은 곳에서 사용되는 화면에서의 표시 크기
soft tab stop : 탭 키를 눌렀을 때 화면에서 움직일 표시 크기, vim에서는 백스페이스 키에도 적용
et(탭 풀어쓰기) : 탭을 모두 공백 문자로 변환해서 파일에 저장
noet : 소프트탭이나 인덴트가 되었을 때, 탭 크기보다 작은 경우에는 공백 문자로, 탭보다 크면 탭 문자로 처리

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

folding  (0) 2010.08.15
ctags & cscope  (0) 2010.08.15
vim 사용법  (0) 2010.06.12
And

Stream

|
Object
ㄴInputStream
   ㄴByteArrayInputStream
   ㄴFileInputStream
   ㄴFilterInputStream
      ㄴBufferedInputStream
   ㄴObjectInputStream
   ㄴPipedInputStream
   ㄴSequenceInputStream
   ㄴStringBufferInputStream
ㄴOutputStream
   ㄴByteArrayOutputStream
   ㄴFileOutputStream
   ㄴFilterOutputStream
      ㄴBufferedOutputStream
      ㄴPrintStream
   ㄴObjectOutputStream
   ㄴPipedOutputStream


'Java' 카테고리의 다른 글

쓰레드  (0) 2010.08.26
오토박싱/언박싱  (0) 2010.08.24
Exception  (0) 2010.08.23
자바 주요 클래스  (0) 2010.08.19
static vs final  (0) 2010.08.17
And

Exception

|
1. 정수를 0으로 나누는 경우 : ArithmeticException
2. 배열의 첨자가 음수 값을 가지는 경우 : IndexOutOfBoundException
3. 배열의 첨자가 배열의 크기를 벗어나는 경우 : IndexOutOfBoundException
4. 유효하지 않은 형변환
5. 입출력 시에 쓰기/읽기 오류가 발생하는 경우
6. 레퍼런스 변수가 null인 상태에서 객체를 참조할 경우 : NullPointerexception

               java.lang.object
               java.lang.Throwable
java.lang.Error             java.lnag.Exception
                                 java.lang.RuntimeException

java.lang.Throwable : 모든 예외의 최상위 클래스
java.lang.Error : 복구가 어렵거나 불가능한 예외 상황으로 일반적으로 오류 메시지를 출력하고 실행이 중단된다.
OutOfMemoryError, StackOverflowError, LinkageError
java.lang.Exception : 예외 처리를 반드시 해야 한다.
ClassNotFoundException, IOException, InterruptedException
java.lang.RuntimeException : 실행 중에 발생할 수 있는 예외 클래스로 예외 처리를 하지 않아도 무방하다.
IllegalArgumentException, IndexOutOfBoundsException, NullPointerException

try {
method();
} catch (Exception e) {
...
} finally {
...
}

'Java' 카테고리의 다른 글

오토박싱/언박싱  (0) 2010.08.24
Stream  (0) 2010.08.23
자바 주요 클래스  (0) 2010.08.19
static vs final  (0) 2010.08.17
내부 클래스 용도  (0) 2010.08.17
And

SHELL

|


shell의 동작 과정
terminal 실행
$를 출력하고 사용자 입력 대기
$ ls -l 입력
fork() 실행
자식 프로세스에서 execve("/bin/ls", "ls", "-l", ...) 실행
부모 프로세스에서 다시 $ 출력하고 사용자 입력 대기


'linux' 카테고리의 다른 글

apt-get  (0) 2010.10.30
gst  (0) 2010.10.22
쉘프로그래밍  (0) 2010.06.05
라이브러리 만들기  (0) 2010.05.31
gdb 사용법  (0) 2010.05.31
And

언어별 코드

|
#접근 제어자
C++는 :을 이용하여 여러 변수에 적용 가능하다.
Java는 변수명, 함수명, 클래스명 앞에 각각 적어야 한다.
C++ : private < protected < (public)
Java : private < (default) < protected < public

[Java]
private : 같은 클래스의 메소드만 접근 가능
default : 같은 패키지 내에서 접근 가능, 기본으로 지정되는 접근 제어자, 생략 가능
protected : 패키지에 관계없이 자손 클래스에서 접근 가능
public : 모든 패키지, 모든 클래스에서 접근 가능
[C++]
private : 같은 클래스의 메소드만 접근 가능, 기본으로 지정되는 접근 제어자, 생략 가능
protected : 자신과 상속받은 클래스에서 접근 가능
public : 모든 클래스 및 함수에서 접근 가능

#배열 선언
Java
int [] array; //스택에 참조 변수의 메모리 4바이트만 할당.
array = new int [5]; //힙에 메모리 20바이트 할당. 0으로 초기화 됨.
--
int [] array = { 1, 2, 3 }; //생성과 동시에 초기화
C++
int array[5]; //스택에 메모리 20바이트 할당. 초기화 안됨.

[Java]
arr1은 생성만 하여 0을 출력, arr2는 생성과 동시에 초기화되어 1을 출력
import java.lang.System;

public class ArrayTest {
    public static void main(String args[]) {
    	int [] arr1 = new int [3];
    	int [] arr2 = { 1, 2, 3 };

    	System.out.println("arr1[0] = " + arr1[0]);
    	System.out.println("arr2[0] = " + arr1[0]);

    }
}

[C++]


#객체 선언
Java

C++


[Java]
반드시 new 연산자로만 생성해야 한다. 힙 영역에 메모리 할당
import java.lang.System;

class Person {
    String name;
    int age;
}

public class PersonTest {
    public static void main(String args[]) {
    	Person p;
    	p = new Person();
    	p.name = "Jack";
    	p.age = 20;
    	System.out.println("p.name : " + p.name);
    	System.out.println("p.age  : " + p.age);
    }
}

[C++]
스택 영역에 할당한 경우
#include <iostream>
#include <string>
using namespace std;

class Person {
public:
    string name;
    int age;
};

int main(int argc, char* argv[]) {
    Person p;
    p.name = "Jack";
    p.age = 20;
    cout << "p.name : " << p.name << endl;
    cout << "p.age  : " << p.age << endl;

    return 0;
}

힙 영역에 할당한 경우
#include <iostream>
#include <string>
using namespace std;

class Person {
public:
    string name;
    int age;
};

int main(int argc, char* argv[]) {
    Person* p = new Person;
    p->name = "Jack";
    p->age = 20;
    cout << "p.name : " << p->name << endl;
    cout << "p.age  : " << p->age << endl;
    delete p;

    return 0;
}


#this
객체 자신을 가리킨다.

Java
자신의 멤버에 접근시 .을 사용한다.
C++
ClassName* const 타입이다.
자신의 멤버에 접근시 ->를 사용한다.

#this() 생성자
Java
같은 클래스 내의 생성자가 오버로딩된 다른 형태의 생성자를 호출할 때 사용한다.
다른 메소드보다 제일 먼저 호출해야 한다.
C++
생성자가 다른 생성자를 호출할 수 없다??

Java


[C++]


#추상 클래스
Java
인스턴스를 생성할 수 없는 하나 이상의 추상 메소드를 가진 미완성 클래스
필드와 메소드, 생성자를 가질 수 있다.
레퍼런스 변수는 선언할 수 있다. 자신의 서브 클래스로 선언된 인스턴스들을 가리킬 수 있다.

abstract class 추상 클래스 이름 {
// 필드 선언
// 일반 메소드 정의
// 생성자 정의
abstract 접근 제어자 리턴 타입 추상 메소드 이름 (매개변수 리스트);
}
C++
객체를 생성할 수 없는 하나 이상의 순수 가상 함수를 가진 클래스
멤버 변수와 멤버 함수, 생성자, 소멸자를 가질 수 있다.

class 추상 클래스 이름 {
// 접근 지정자
// 멤버 변수 선언
// 멤버 함수 선언
// 생성자, 소멸자 선언
virtual 리턴 타입 멤버 함수 이름 (매개변수 리스트) = 0;
}


Java


[C++]




#인터페이스
자바에서 다중 상속을 가능하게 하기 위해 제공
Java
상수 또는 추상 메소드들만 포함
인터페이스의 모든 메소드는 내부적으로 public이다.
인터페이스 내부의 메소드에 접근 지정자가 명시되어 있지 않다면 서브 클래스에서는 접근 지정자를 지정할 수 없으므로 public으로 선언해야 한다.


C++



Java


[C++]





#
Java


C++



Java


[C++]





#
Java


C++



Java


[C++]





#
Java


C++



Java


[C++]





#
Java


C++



Java


[C++]





#
Java


C++



Java


[C++]





#
Java


C++



Java


[C++]





#
Java


C++



Java


[C++]



-- end --

'diff C++ Java C#' 카테고리의 다른 글

생성자, 상속, 오버라이딩  (0) 2010.08.19
클래스간의 형변환  (0) 2010.08.18
And

[AlertDialog2]

|
AlertDialogTest2.java

setTitle() : 제목 설정
setMessage() : 아이콘 설정
setPositiveButton("text", listener) : 버튼 생성, listener를 null로 설정하면 버튼을 눌렀을 때 다이얼로그가 사라지며 아무 동작 안함.
listener를 인터페이스로 구현해 놓았으므로 DialogInterface.OnClickListener() 어댑터를 생성하여 onClick()을 오버라이딩하여 작성한다.
AlertDialogTest2.java
package net.itisn.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class AlertDialogTest2 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 View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(
				        AlertDialogTest2.this);
				builder.setTitle("Notice");
				builder.setMessage("Dialog is opened. Congraturation!");
				builder.setIcon(R.drawable.icon);
				// builder.setPositiveButton("Close", null); // 닫는 버튼 생성
				builder.setPositiveButton("Close",
				        new DialogInterface.OnClickListener() {

					        @Override
					        public void onClick(DialogInterface dialog,
					                int which) {
						        // TODO Auto-generated method stub

					        }
				        });
				builder.show();
			}
		});
	}
}


-

'Android' 카테고리의 다른 글

[MyHandlerTest]  (0) 2010.09.28
[ImageButton, Toast]  (0) 2010.08.23
[AlertDialog]  (0) 2010.08.18
[MenuTest]  (0) 2010.08.18
[ImageView]  (0) 2010.08.17
And

자바 주요 클래스

|
Object obj;
boolean equals() : 두 객체의 내용이 같은지 비교한다. (사용자 정의 클래스의 객체인 경우에는 오버라이딩하여 각 필드마다 같은지 비교해야 한다.??)
== 연산자는 참조변수가 가리키는 인스턴스가 같은지 비교한다.
String str1 = "java";
String str2 = "java";
String str3 = new String("java");

str1 == str2 : true
str1 == str3 : false
str2 == str3 : false

str1.equals(str2) : true
str1.equals(str3) : true
str2.equals(str3) : true

Class getClass() : 객체의 클래스 이름을 Class 형으로 반환
int hashCode() : 객체의 해시 코드를 반환
notify()
notifyAll()
String toString() : 객체의 문자열을 반환
wait()

String 클래스
한 번 생성된 객체는 절대 변하지 않는다. --> 메모리 낭비 심함
String str1 = "Java";
str1.replace("Java", "C"); -> 힙에 새로운 String 객체 "C"가 생성
println(str1); -> 여전히 "Java"를 출력
str1 = str1.replace("Java", "C"); -> str1이 "C"를 가리키게 한다.
println(str1); -> "C"를 출력

StringBuffer 클래스
동적 문자열 처리가 가능하다. 속도가 몇 십 배 느려질 수 있다.

'Java' 카테고리의 다른 글

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

생성자, 상속, 오버라이딩

|
초기화 : 변수가 메모리 할당을 진행하는 동시에 값을 설정하는 것
생성자 : 인스턴스가 생성되는 동시에 값을 설정하는 것

디폴트 생성자 : 프로그래머가 생성자를 명시적으로 만들지 않아도 자바 컴파일러가 제공해 주는 생성자. 모든 클래스에 적용
public ClassName() { }
단, 프로그래머가 생성자를 하나라도 생성하였을 경우에는 제공되지 않는다. 따라서 인자가 없는 생성자를 사용하는 경우 반드시 작성해 주어야 한다.

this() 생성자
같은 클래스 내의 생성자가 다른 형태의 생성자를 호출할 때 사용
반드시 다른 어떤 메소드보다 먼저 호출되어야 한다. (변수 대입은 상관없는가?)
* 생성자 내부의 첫 문장으로 this()가 기술되어야 한다.
* this()는 생성자에서만 사용할 수 있다.

오버라이딩할 때 상속받은 메소드도 포함하여 작성하기
super.method();

상속에서의 super() 생성자
명시하지 않아도 자동적으로 호출된다.
이 때, 부모 클래스에서 인자가 있는 생성자가 있다면 반드시 인자가 없는 생성자를 명시해 주어야 한다.
왜냐하면 자식 클래스에서 인자가 없는 생성자를 쓸 수도 있기 때문이다.

슈퍼 클래스에 인자가 있는 생성자만 존재하는 경우에는 super(인자)로 직접 호출해야 한다. 첫문장으로 기술되어야 한다.

인터페이스가 인터페이스를 상속받을 때에는 extends를 쓴다.


'diff C++ Java C#' 카테고리의 다른 글

언어별 코드  (0) 2010.08.21
클래스간의 형변환  (0) 2010.08.18
And

클래스간의 형변환

|
C++
객체간의 형변환
HTMLWriter hw;
DocWriter dw;
hw = dw; //실패
dw = hw; //성공, 부모 객체와 자식 객체에 공통적으로 있는 멤버들이 1:1로 대입된다. dw의 멤버함수가 호출된다.

포인터간의 형변환, 레퍼런스간의 형변환
DocWriter dw;
HTMLWriter* phw = &dw; //실패

HTMLWriter hw;
DocWriter* pdw = hw; //성공, 자식 객체(hw)의 멤버변수가 사용된다. 부모 객체(pdw)의 멤버함수가 호출된다. virtual인 경우 자식 객체의 멤버함수가 사용된다.

업캐스트 & 다운캐스트
HTMLWriter hw;
DocWriter* pdw = &hw; //업캐스트
HTMLWriter* phw = (HTMLWriter*)pdw; //다운캐스트

DocWriter dw;
HTMLWriter* phw = dw; //다운캐스트 안됨
HTMLWriter* phw = (HTMLWriter*)dw; //다운캐스트







Java
인스턴스 변수의 초기화가 가능하다.
부모 클래스의 변수를 사용 (Variable Shadowing)
자식 클래스의 메소드를 사용 (Polymorphism)
class A {
	int x = 1;
	int y = 2;
	
	void disp() {
		System.out.println("A class, " + x);
	}
}

class B extends A {
	int x = 10;
	int y = 20;
	int z;
	
	void disp() {
		System.out.println("B class, " + x);
	}
}

public class PolymorphismTest {
	public static void main(String args[]) {
		//UpCast a.x = 1
		B b = new B();
		A a = b; //A a = (A)b;
		System.out.println(a.x);
		a.disp();
	}
}




기본 매개변수 : 정적 바인딩 (선행 바인딩)
가상 함수 : 동적 바인딩 (지연 바인딩)

상속받은 매개변수는 절대 재정의해서는 안된다. 정적 바인딩이 되므로 부모 클래스의 가상함수에서 정의된 매개변수의 값이 들어간다.


C++
*
생성자나 멤버함수를 통해 멤버변수의 초기화가 가능하다.
인자가 없는 생성자로 생성한 경우, 부모 클래스의 멤버변수, 멤버함수가 사용된다.
인자가 있는 생성자로 생성한 경우, 자식 클래스의 멤버변수, 부모 클래스의 멤버함수가 사용된다.
부모 클래스의 멤버함수 앞에 virtual을 붙이면 자식 클래스의 멤버변수, 멤버함수가 사용된다.

잘못 작성한 경우
class A { int x, y; };
class B : public A { int x, y, z; };
이 경우 A의 x와 B의 x는 서로 다른 멤버변수이다.
B b;
b.x는 B의 x이고, b.A::x가 A의 x이다.
상속받은 멤버변수는 A::x가 된다.


복사 생성자가 작성되어 있으면 복사 생성자 호출시 디폴트 생성자를 호출하지 않는다.
또한 초기화 할 때에만 복사 생성자를 호출할 수 있다.
복사 생성자를 작성하지 않고 사용할 경우 멤버 변수를 1:1로 복사한다.

부모 클래스에 생성자가 여러 개일 경우
자식 클래스에서 각각에 맞는 부모 클래스의 생성자를 호출해 주어야 한다.
그렇지 않으면 부모 클래스의 디폴트 생성자를 호출하게 된다.



-

'diff C++ Java C#' 카테고리의 다른 글

언어별 코드  (0) 2010.08.21
생성자, 상속, 오버라이딩  (0) 2010.08.19
And

[AlertDialog]

|

1. Dialog ID를 생성한다.
2. onCreateDialog(int id)를 오버라이드한다.
3. AlertDialog의 서브클래스 Builder로 builder를 생성해 다이얼로그를 설정한다.
4. AlertDialog로 alert를 생성해 builder.create()로 다이얼로그를 생성한다.
5. onCreate()에 showDialog()로 다이얼로그를 보이게 한다.
AlertDialogTest.java
package net.itisn.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;

public class AlertDialogTest extends Activity {
    /** Called when the activity is first created. */
	static final int QUIT_ID = 0;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        showDialog(QUIT_ID);
    }
    
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to exit")
		.setCancelable(false)
		.setPositiveButton("Yes",
			new DialogInterface.OnClickListener() {
					
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					AlertDialogTest.this.finish();
				}
			})
		.setNegativeButton("No",
			new DialogInterface.OnClickListener() {
					
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.cancel();
				}
			});
		AlertDialog alert = builder.create();
		
		//return super.onCreateDialog(id);
		return alert;
	}
}

-

'Android' 카테고리의 다른 글

[ImageButton, Toast]  (0) 2010.08.23
[AlertDialog2]  (0) 2010.08.19
[MenuTest]  (0) 2010.08.18
[ImageView]  (0) 2010.08.17
[LifeCycle]  (0) 2010.08.17
And

[MenuTest]

|

메뉴 생성하기
1. static final로 itemid를 만든다.
2. onCreateOptionMenu(Menu menu)를 오버라이드하여 menu.add()로 메뉴를 추가한다.
3. onOptionsItemSelected(MenuItem item)를 오버라이드하여 메뉴와 액션을 연결한다.

컨텍스트 메뉴 생성하기
1. static final로 itemid를 만든다.
2. onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo info)를 오버라이드하여 menu.add()로 메뉴를 추가한다.
3. onContextedItemSelected(MenuItem item)를 오버라이드하여 메뉴와 액션을 연결한다.
4. 메뉴를 출력하고자 하는 View의 아이디를 지정한다.
4. onCreate(Bundle savedInstanceState)에 registerForContextMenu(View view)로 컨텍스트 메뉴를 등록한다.

MenuTest.java
package net.itisn.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class MenuTest extends Activity {
    /** Called when the activity is first created. */
	static final int MENU_NEW_GAME = 0;
	static final int MENU_QUIT = 1;
	static final int EDIT_ID = 2;
	static final int DELETE_ID = 3;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //기본 생성되는 TextView는 id가 없다. 따라서 id를 적어 주어야 한다.
        //@+id/TextView01
	registerForContextMenu(this.findViewById(R.id.TextView01));
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		menu.add(0, MENU_NEW_GAME, 0, "New Game");
		menu.add(0, MENU_QUIT, 0, "Quit").setIcon(R.drawable.icon);
		
		return super.onCreateOptionsMenu(menu); //equals to return true.
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()) {
		case MENU_NEW_GAME:
			//newGame();
			return true;
		case MENU_QUIT:
			//quit();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		menu.add(0, EDIT_ID, 0, "Edit");
		menu.add(0, DELETE_ID, 0, "Delete");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch (item.getItemId()) {
		case EDIT_ID:
			//editNote(Info.id);
			return true;
		case DELETE_ID:
			//deleteNote(Info.id);
		default:
			return super.onContextItemSelected(item);
		}
	}
	
}


-

'Android' 카테고리의 다른 글

[AlertDialog2]  (0) 2010.08.19
[AlertDialog]  (0) 2010.08.18
[ImageView]  (0) 2010.08.17
[LifeCycle]  (0) 2010.08.17
[ShapeEx]  (0) 2010.08.16
And

static vs final

|
static : 클래스 필드 정의시 사용
final : 상수로 만들 때 사용

인스턴수마다 상수를 갖는다는 것은 별 의미가 없다. 어차피 같은 값이므로.
따라서 상수는 static final 로 선언한다.


죄송합니다. lmb543.egloos.com의 아임머신님은 
글 내용이 다른 곳에 복사되는 것을 원하지 않습니다.
출처링크를 사용해주세요.

[자바문법] static, final 수정자

'Java' 카테고리의 다른 글

Exception  (0) 2010.08.23
자바 주요 클래스  (0) 2010.08.19
내부 클래스 용도  (0) 2010.08.17
주민등록번호 추출  (0) 2010.08.16
자바 소수점 출력  (0) 2010.08.13
And
prev | 1 | 2 | 3 | next