==========================================================================================

C#

==========================================================================================


<C#>


 ==LINQ ( Language INtergrated Query )

:c# 언어에 통합된 데이터 질의 기능


-From  : 어떤 데이터 집합 ?

-Where : 어떤 값 데이터 ?

-Select :어떤 항목 추출 ?


=from 범위변수 in 데이터 원본(반드시 IEnumerable<T> 인터페이스)

=where : 필터 ( 조건 )

=orderby : 정렬 ( ascending / descending )

=select : 추출 - IEnumverable < T >  T : select 문에의해 결정


=


using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LINQ_EX
{
    
class Profile
    {
        
public string Name { get; set; }
        
public int Height { get; set; }
    }
    
class Program
    {
        
static void Main(string[] args)
        {
          
 // 원본 데이터 : 반드시 IEnumerable 인터페이스 
            Profile[] arrProfile = {
                                       
new Profile(){Name="정우성", Height = 186},
                                       
new Profile(){Name="김태희", Height = 158},
                                       
new Profile(){Name="고현정", Height = 172},
                                       
new Profile(){Name="이문세", Height = 178},
                                       
new Profile(){Name="하동훈", Height = 171},
                                   };


             
// 일반 - 키가 175 미만인 사람 오름차순 정렬
            List
<Profile> profiles = new List<Profile>();
            foreach(Profile P in arrProfile)
            {
                
if (P.Height < 175)
                    profiles.Add(P);
            }

            profiles.Sort(
                (profile1, profile2) 
=>
                {
                    
return profile1.Height - profile2.Height;
                });

             // 출력
            foreach (var p in profiles)
                Console.WriteLine(
"{0}, {1}", p.Name, p.Height);

            
// LINQ로 구현
            Console.WriteLine("\nLINQ");
            
var Lprofiles = from p in arrProfile       // arrProfile 원본 데이터로 부터
                           where p.Height 
< 175    // Heifht 가 175미만인 객체만 골라
                           orderby p.Height         // Height 기본 오름차순 (ASCENDING) 정렬
                           select p;                 // p객체를 추출

             // 출력
            foreach (var p in Lprofiles)
                Console.WriteLine(
"{0}, {1}", p.Name, p.Height);

        }
    }
}







=여러개의 데이터 원본에 질의

:from 중첩 사용


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FromFrom
{
    
class Class
    {
        
public string Name { get; set; }
        
public int[] Score { get; set; }
    }

    
class Program
    {
        
static void Main(string[] args)
        {
            Class[] arrClass 
=
            {
                
new Class(){Name = "연두반", Score = new int[]{99807024}},
                
new Class(){Name = "분홍반", Score = new int[]{60458772}},
                
new Class(){Name = "파랑반", Score = new int[]{92308594}},
                
new Class(){Name = "노랑반", Score = new int[]{9088017}},
            };

            var classed 
=   from c in arrClass
                            from s in c.Score
                                where s
<60
                                orderby s
                            select 
new { c.Name, Lowest =
s};

            foreach(var c in classed)
                Console.WriteLine(
"낙제 : {0} ({1})", c.Name, c.Lowest);
        }
    }
}






==========================================================================================

C++

==========================================================================================

<C++>



=중첩 클래스


#include <iostream>
using namespace std;

class Outer
{
    
private:
        
class inner
        {

             private:
                
int memA;
            
public:
                inner(
int a) : memA(a)
                {
                }
                
int GetA()
                {
                    
return memA;
                }
        }
obj;
    
public:
        Outer(
int a) :obj(a)
        {
        }
        
void OutOuter()
        {
            cout 
<< "멤버 값 = " << obj.GetA() << endl;
        }
};

int main()
{
    
Outer O(345);
    
//Inner I(678);   // 에러

    O.OutOuter();
    
return 0;
}






-

#include <iostream>
using namespace std;

void func()
{
    
struct dummy
    {
        
static void localfunc()
        {
            cout 
<< "저는 func 안에서만 정의됩니다.\n";
        }
    };
    
dummy::localfunc();
}

int main()
{
    func();
   
//localfunc()   // 에러
    return 0;
}











-cf) SQL (Stuructured Query(질의) Language) - 데이터 베이스에 던지는 질의언어

-오라클

-MSSQL

-MYSQL



==다형성


=가상함수

:객체 기반으로 호출 가능

:C++은 main()가 class에 속해있지 않음


-함수 동적 링킹(컴파일시 X) => 실행시 완성(코드 분석 힘들다)



(자바 : DEFAULT로 OBJECT CLASS 상속) => OBJECT * => 모두 가리킬 수 있음


=

#include <iostream>
using namespace std;

class CAR
{
    
public:
        
void print() 
        {
            cout 
<< "나는 CAR CLASS다\n";
        }
};

class BMW : public CAR
{
    
public:
        
void print() // 오버라이딩
        {
            cout 
<< "나는 BMW CLASS다\n";
        }
};

int main()
{
    BMW obj;
    
BMW *bp = &obj;
    
bp->print(); // bp에의해 결정 => BMW
    CAR *cp = &obj;
    
cp->print(); // cp에의해 결정 => CAR

    return 0;
}








=파생클래스의 클래스포인터(bp)는 기반클래스의 객체(obj1)를 가리킬 수 없다


#include <iostream>
using namespace std;

class CAR
{
    
public:
        
void print() 
        {
            cout 
<< "나는 CAR CLASS다\n";
        }
};

class BMW : public CAR
{
    
public:
        
void print() // 오버라이딩
        {
            cout 
<< "나는 BMW CLASS다\n";
        }
};


int main()
{
    BMW obj;
    BMW *bp 
= &obj;
    bp-
>print(); // bp에의해 결정 => BMW
    CAR *cp = &obj;
    cp-
>print(); // cp에의해 결정 => CAR
//    CAR obj1;
//    bp 
= &obj1; // 에러

    return 0;
}





=


#include <iostream>
using namespace std;

class CAR
{
    
public:
        
void print() 
        {
            cout 
<< "나는 CAR CLASS다\n";
        }
};

class BMW : public CAR
{
    
public:
        
void print() // 오버라이딩
        {
            cout 
<< "나는 BMW CLASS다\n";
        }
};

class TICO : public CAR
{
    
public:
        
void print() // 오버라이딩
        {
            cout 
<< "나는 TICO CLASS다\n";
        }
};

int main()
{
    BMW obj;
    
BMW *bp = &obj;
    bp-
>print(); // bp에의해 결정 => BMW
    CAR *cp = &obj;
    cp-
>print(); // cp에의해 결정 => CAR
//    CAR obj1;
//    bp 
= &obj1; // 에러
    TICO obj2;
    
TICO * tp;
    tp-
>print(); // tp에의해 결정 => TICO

    
return 0;
}





=> 기반 클래스의 클래스 포인터는 파생 클래스의 OBJ를 가리킬 수 있다

#include <iostream>
using namespace std;

class CAR
{
    
public:
        
void print() 
        {
            cout 
<< "나는 CAR CLASS다\n";
        }
};

class BMW : public CAR
{
    
public:
        
void print() // 오버라이딩
        {
            cout 
<< "나는 BMW CLASS다\n";
        }
};

class TICO : public CAR
{
    
public:
        
void print() // 오버라이딩
        {
            cout 
<< "나는 TICO CLASS다\n";
        }
};

int main()
{
    BMW obj;
    BMW *bp 
= &obj;
//    bp->print(); 
    CAR *cp = &obj;
    
cp->print(); // cp에의해 결정 => CAR
//    CAR obj1;
//    bp 
= &obj1; // 에러
    TICO obj2;
    cp-
>obj2;
    
cp->print(); // cp에의해 결정 -> CAR
    TICO * tp;
    tp-
>print();

    
return 0;
}







=VIRTUAL 

=> 기반 클래스의 클래스 포인터는 파생 클래스의 OBJ를 가리킬 수 있다

=> 최종 가리킨 OBJ를 기반으로 호출


#include <iostream>
using namespace std;

class CAR
{
    
public:
        
virtual void print() // virtual => 최종 객체 기반으로 호출
        {
            cout 
<< "나는 CAR CLASS다\n";
        }
};

class BMW : public CAR
{
    
public:
        
void print() // 오버라이딩
        {
            cout 
<< "나는 BMW CLASS다\n";
        }
};

class TICO : public CAR
{
    
public:
        
void print() // 오버라이딩
        {
            cout 
<< "나는 TICO CLASS다\n";
        }
};

int main()
{
  
  BMW obj;
//    BMW *bp = &obj;
//    bp-
>print(); // bp에의해 결정 => BMW
    CAR *cp = &obj; // 파생 클래스의 객체 모두를 가리킬 수 있다
    cp-
>print(); // virtual => 최종객체 CP = BMW 에의해 결정 => BMW
//    CAR obj1;
//    bp 
= &obj1; // 에러
    TICO obj2;
//    TICO * tp;
//    tp-
>print();
    cp = &obj2;
    cp-
>print(); // virtual => 최종객체 CP = TICO 에의해 결정 => TICO
    
return 0;
}









=virtual


#include <iostream>
using namespace std;

class Base
{
    
public:
        virtual void OutMessage()
        {
            cout 
<< "Base Class\n";
        }
};

class Derived : public Base
{
    
public:
        virtual void OutMessage()
        {
            cout 
<< "Derived Class\n";
        }
};

void Message(Base *pB)
{
    pB-
>OutMessage();
}

int main()
{
    Base B;
    Derived D;


    Message(
&B);
    Message(
&D);

    
return 0;
}







=P219~연산자


=복합 대입 연산자

#include <iostream>
using namespace std;

class Time
{
    
private:
        
int hour, min, sec;

    
public:
        Time(){}
        Time(
int h, int m, int s)
        {
            hour 
= h;
            min 
= m;
            sec 
= s;
        }
        
void OutTime()
        {
            cout 
<< hour << ":" << min << ":" << sec << endl;
        }
        Time 
&operator +=(int s)
        {
            sec +
= s;
            min +
= sec/60;
            sec %
= 60;
            hour +
= min/60;
            min %
=60;
            
return *this
;
        }

};

int main()
{
    Time A(
1,1,1);

    A+
=62;
    A.OutTime();
    
return 0;
}








=[] 배열연산자


#include <iostream>
using namespace std;

class Time
{
    
private:
        
int hour, min, sec;
    
public:
        Time(){}
        Time(
int h, int m, int s)
        {
            hour 
= h;
            min 
= m;
            sec 
= s;
        }
        
void OutTime()
        {
            cout 
<< hour << ":" << min << ":" << sec << endl;
        }
        
int &operator [](int what)
        {
            
switch (what)
            {
                
case 0:
                    
return hour;
                
case 1:
                    
return min;
                
default:
                
case 2:
                    
return
 sec;
            }
        }

        
const int &operator [](int what) const
        {
            
switch (what)
            {
                
case 0:
                    
return hour;
                
case 1:
                    
return min;
                
default:
                
case 2:
                    
return sec;
            }
        }
};


int main()
{
    Time A(
1,1,1);
    
const Time B(7,7,7);

    A[
0]=12;
    cout 
<< "현재 " << A[0] << "시 입니다\n";
    
//B[0]=8; // 에러 const => 수정 불가 read only
    cout << "현재 " << B[0] << "시 입니다\n";
    
return 0;
}
















=[]


#include <iostream>
#include <string.h>
using namespace std;

class StuList
{
    
private:
        
struct Student
        {
            
char Name[10];
            
int StNum;
        }S[
30];

    
public:
        StuList()
        {
            strcpy(S[
0].Name, "이승만");S[0].StNum=1;
            strcpy(S[
1].Name, "박정희");S[1].StNum=3;
            strcpy(S[
2].Name, "전두환");S[2].StNum=6;
            strcpy(S[
3].Name, "노태우");S[3].StNum=9;
            strcpy(S[
4].Name, "김영삼");S[4].StNum=15;
            strcpy(S[
5].Name, "김대중");S[5].StNum=17;
            strcpy(S[
6].Name, "노무현");S[6].StNum=20;
            strcpy(S[
7].Name, "??????");S[7].StNum=100;
        }
        
int operator[](const char * Name)
        {
            
for(int i=0;;++i)
            {
                
if(strcmp(S[i].Name,Name)==0)
                    
return S[i].StNum;
                
if(S[i].Name[0]=='?')
                    
return -1
;
            }
        }

};


int main()
{
    StuList SL;

    cout 
<< "김영삼 학생의 학번은 " << SL["김영삼"] <<" 번 입니다\n";
    
return 0;
}








= -> 멤버참조연산자

#include <iostream>
#include <string.h>
using namespace std;

struct Author
{
    
char Name[32];
    
char Tel[24];
    
int Age;
};

class Book
{
    
private:
        
char Title[32];
        Author Writer;

    
public:
        Book(
const char *aTitle, const char * aName, int aAge)
        {
            strcpy(Title, aTitle);
            strcpy(Writer.Name, aName);
            Writer.Age
=aAge;
        }
        Author *
operator->()
        {
            
return &
Writer;
        }

        
const char *GetTitle()
        {
            
return Title;
        }
};

int main()
{
    Book Hyc(
"혼자 연구하는 C/C++","김상형",25);
    cout 
<< "제목: " << Hyc.GetTitle() <<"저자: " << Hyc->Name << "저자나이: " <<  Hyc->Age << endl;
    
return 0;
}







=()연산자


#include <iostream>
using namespace std;

class Sum
{
    
public:
        
int operator()(int a, int b, int c, int d)
        {
            
return a + b + c + d;
        }
        
double operator()(double a, double b)
        {
            
return
 a + b;
        }

};

int main()
{
    Sum S;
    cout 
<< "1 2 + 3 + 4 = " <<  S(1234<< endl;
    cout 
<< "1.2 + 3.4 = : " <<  S(1.23.4<< endl;
    
return 0;
}











-()

#include <iostream>
#include <string.h>
using namespace std;

class ScoreManager
{
    
private:
        
// 성적을 저장하는 여러가지 멤버 변수들
        int ar[3][5][10][4];
    
public:
        ScoreManager()
        {
            memset(ar, 
0sizeof(ar));
        }
        
int &operator()(int Grade, int Class, int StNum, const char * Subj)
        {
            
return ar[Grade][Class][StNum][0
];
        }

};

int main()
{
    ScoreManager SM;

    cout 
<< "1학년 2반 3번 학생의 국어 성적 = " << SM(123"국어") << endl;
    SM(
234"산수"= 99;
    
return 0;
}









=new / delete


#include <iostream>
#include <stdlib.h>
using namespace std;

void *operator new(size_t t)
{
    
return malloc(t);
}


void operator delete(void *p)
{
    free(p);
}

int main()
{
    
int *pi = new int;
    *pi 
= 1234;
    cout 
<< *pi << endl;
    
delete pi;
    
return 0;
}











'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150619  (0) 2015.06.21
20150618  (0) 2015.06.18
20150616  (0) 2015.06.16
20150615  (0) 2015.06.16
20150612  (0) 2015.06.14
Posted by ahj333
,

==========================================================================================

C#

==========================================================================================


<C#>


==람다식


-익명 메소드를 만든느 또 하나의 방법

-LISP언어






=cf) Ruby on Rails : 웹언어


=형식유추

-람다식의 매개 변수를 컴파일러가 유추해주는 기능









=

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LambdaExepress
{
    
class Program
    {

//람다식 - delegate 활용 (delegate 선언 필요 O)
        
delegate int Calculate(int a, int
 b);
        delegate 
void DoSomething();


         
static void Main(string[] args)
        {
            //delegate 활용
            Calculate calc1 = delegate(int a, int b)
            {
                
return a + b;
            };
            
int temp = calc1(35);
            Console.WriteLine(temp);


           
 //람다식(Lambda Expression) 활용
            Calculate calc2 = (a, b) => a - b;

            temp 
= calc2(34);
            Console.WriteLine(temp);

            
//람다구문(Statement Lambda) 활용
            DoSomething DoIt = () =>
            {
                Console.WriteLine(
"{0} + {1}= {2}"123
);
            };

            DoIt();

 

//람다식 - Func 델리게이트 : 반환형 O (delegate 선언 필요 X)          

         


             
//Func 델리게이트 활용 (인자 2 마지막 args는 반환,out)
            Func<intintint> calc3 = (x,y) => x * y;

            temp 
= calc3(23);
            Console.WriteLine(temp);

            
//Func 델리게이트 활용 (인자 1 마지막 args는 반환,out)
            Func<int, int> calc5 = (x) => x * 2;
            temp 
= calc5(2);
            Console.WriteLine(temp);


//람다식 - Action 델리게이트 : 반환형 x (delegate 선언 필요 X)
            
//Action 반환형 없음
            Action<doubledouble> calc4 = (x, y) =>
            {
                
double p = x / y;
                Console.WriteLine(
"Action<T1,T2>({0},{1}:{2:f3}) "
, x, y, p);
            };


            calc4(
7,3);
        }
 
    }
    
class Myclass
    {
        Program pr1
= new Program();
    }

}






=Action 델리게이트

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ActionDelegate
{
    
class Program
    {
        
static void Main(string[] args)
        {
            
//매개변수 없는 버전
            Action act1 = () => Console.WriteLine("Action()");

            act1();

            
int result = 0;
            
//매개변수 1개
            Action<int> act2 = (x) => result = x * x;


            act2(
3);            
            Console.WriteLine("result : {0}", result);


              
//매개변수 2개... ~ 16개
            Action
<doubledouble> act3 = (x, y) =>
            {
                
double pi = x / y;
                Console.WriteLine(
"Action<T1, T2>({0}, {1}) : {2}"
, x, y, pi);
            };

            act3(
22.07.0);
        }
    }
}






=문형식의 람다식









=Func 델리게이트


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FuncTest
{
    
class Program
    {
        
static void Main(string[] args)
        {
            Func
<int> func1 = () => 10;
            Console.WriteLine(
"func1() : {0}"func1());

            Func
<intint> func2 = (x) => x * 2;
            Console.WriteLine(
"func2(4) : {0}"func2(4));

            Func
<doubledoubledouble> func3 =
                (x, y) =>
 x / y;
            Console.WriteLine(
"func3(22/7) : {0}"func3(227));
        }
    }
}







= 식트리  ( LINQ :C#코드가 아님 => 실행 중 컴파일 해서 사용 가능 하도록 함)

-EXPRESSION :

-팩토리 메소드

-람다 : (a, b) => 1*2 + (a-b) : (a, b)는 1*2 + (a-b)로 이동(=> : move) 시킨다.


=

using System;
using System.Linq.Expressions;

namespace UsingExpressionTree
{
    
class Program
    {
        
/*
        static void Main(string[] args)
        {
            //1*2+(x-y)
            Expression const1 
= Expression.Constant(1);
            Expression const2 
= Expression.Constant(2);

            Expression leftExp 
= Expression.Multiply(const1, const2); // 1 * 2

            Expression param1 
= Expression.Parameter(typeof(int)); // x
            Expression param2 
= Expression.Parameter(typeof(int)); // y

            Expression rightExp 
= Expression.Subtract(param1, param2); // x - y
            Expression exp 
= Expression.Add(leftExp, rightExp);

            Expression
<Func<int, int, int>> expression =
                Expression<Func<int, int, int>>.Lambda<Func<int, int, int>>(
                    exp, new ParameterExpression[]{
                        (ParameterExpression)param1,
                        (ParameterExpression)param2});

            Func
<int, int, int> func = expression.Compile();

            //x 
= 7, y = 8
            Console.WriteLine("1 * 2 + ({0}-{1}) 
= {2}", 7, 8, func(7, 8));
        }
        *///람다식으로 변경
        static void Main(string[] args)
        {
            
Expression<Func<intintint>> expression =
                (a, b) => 1 * 2 + (a - b);
            
            Func
<intintint> func =
 expression.Compile();

            
//x = 7, y = 8
            Console.WriteLine("1 * 2 + ({0}-{1}) = {2}"78func(78));
        }
    }
}






=구글 내 위치 API => 코드를 줄수는 없음 / 필요한 사람이 원하는 곳에 넣을 때 EXPRESS를 이용해서 코드를 가리키는 위임자를 만들어 사용)



=연습문제


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LamdaTest
{
    
class Program
    {
        
/*
        static void Main(string[] args)
        {
            int[] array 
= { 11, 22, 33, 44, 55 };

            foreach (int a in array)
            {
                Action action 
= new Action
                (
                    delegate()
                    {
                        Console.WriteLine(a*a);
                    }
                );
                action.Invoke();
            }


        }*/

         //같은 결과 되도록 람다식으로 수정

        static void Main(string[] args)
        {
            
int[] array = { 1122334455 };

            
Func<int, string> test =
                (x) => (x * x).ToString();

            
            foreach (
int a in array)
            {                
                Console.WriteLine(
test(a));
            }

        }
    }
}





==========================================================================================

C++

==========================================================================================

<C++>



=다중상속의 문제점

class A

{

        int a;

}

class B public A

class C : public A

class D : public B, public C

{

        a = 3 // 어느 a인지 알 수 없음

};

:다이아몬드 계층도


=> 해결법

1. :: 연산자 사용

-B::a

-C::a


2. vitual

=가상기반 클래스

class B : virtual public A

class C : vittual public A

class D : public B, public C

{

};


=포함


#include <iostream>
#include <string.h>
using namespace std;

class Date
{
    
protected:
        
int year, month, day;
    
public:
        Date(
int y, int m, int d)
        {
            year 
= y;
            month 
= m;
            day 
= d;
        }
        
void OutDate()
        {
            cout 
<< year << "/" << month << "/" << day << endl;
        }
};

class Product
{
    
private:
        
char Name[64];
        
char Company[32];
        
Date ValidTo;
        
int Price;
    
public:
        Product(
const char * aN, const char * aC, int y, int m, int d, int aP) : ValidTo(y, m, d)
        {
            strcpy(Name, aN);
            strcpy(Company, aC);
            Price 
= aP;
        }
        
void OutProduct()
        {
            cout 
<< "이름    :" << Name << endl;
            cout 
<< "제조사  :" << Company << endl;
            cout 
<< "유효기간:";
            ValidTo.OutDate();
            
//puts("");
            cout << "가격    :" << Price << endl;
               
        }
};



int main()
{
    Product S(
"새우깡""농심"2009815900);
    S.OutProduct();
        
return 0;
}



=private 상속


#include <iostream>
#include <string.h>
using namespace std;

class Date
{
    
protected:
        
int year, month, day;
    
public:
        Date(
int y, int m, int d)
        {
            year 
= y;
            month 
= m;
            day 
= d;
        }
        
void OutDate()
        {
            cout 
<< year << "/" << month << "/" << day << endl;
        }
};

class Product : private Date
{
    
private:
        
char Name[64];
        
char Company[32];
       
 //Date ValidTo;
        int Price;
    
public:
        Product(
const char * aN, const char * aC, int y, int m, int d, int aP) : Date(y, m, d)
        {
            strcpy(Name, aN);
            strcpy(Company, aC);
            Price 
= aP;
        }
        
void OutProduct()
        {
            cout 
<< "이름    :" << Name << endl;
            cout 
<< "제조사  :" << Company << endl;
            cout 
<< "유효기간:";
            OutDate();
            
//puts("");
            cout << "가격    :" << Price << endl;
               
        }
};



int main()
{
    Product S(
"새우깡""농심"2009815900);
    S.OutProduct();
        
return 0;
}



-결과 동일






=두개 이상의 Date 정보(제조일자, 유효기간) 사용 해야 할 경우 => 포함 O / private 상속 X


-포함

Date MunuFact;

Date ValidTo;


-private 상속

class Product : private Date, private Date // 에러


=




=인터페이스 상속(선언) / 구현 상속(정의)


순수 가상 함수       : 가상함수 이나, 함수의 정의부분이 없고, 선언 부분만 있는 함수
                        :      모든 파생 클래스마다 동일한 역활을 하는 
고유의 동작을 필요로 하게 될 때

                        : 다형성
가상 함수             : 파생 클래스에서 가상함수를 받는 함수가 없다면,

                                기본 클래스 함수가 호출되고
                      있다면,

                                파생 클래스의 가상 함수를 호출시켜주는 매체가 되는 함수

                        : 모든 파생 클래스마다 동일한 역활을 하는 일반적인 동작을 필요로 하게 될 때

비 가상 함수 : 일반 멤버 함수, 
                :모든 파생 클래스마다 동일한 역활을 하는 
절대적인 동작을 필수로 하게 될 때




'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150618  (0) 2015.06.18
20150617  (0) 2015.06.17
20150615  (0) 2015.06.16
20150612  (0) 2015.06.14
20150611  (0) 2015.06.11
Posted by ahj333
,

==========================================================================================

C#

==========================================================================================


<C#>


=구구단

2단

3단 

...뽑아 활용(index -X)


- 잘라내기

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _20150612_1_MultiTable
{
          
    
class multi
    {
        
private int idan;

        
public multi(int id)
        {
            idan 
= id;
        }           
  
        
public string[] multiple()
        {
            string[] sone 
= new string[9];
            
int[] res = new int[9];
            
for(int i = 1; i < 10; ++i)
                sone[i-
1= idan + " * " + i + = " + ((idan)*i);
            
return sone;
        }
    }
    
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }

        
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string words 
= ComboBox.Text;
            string[] temp 
= words.Split(new Char[] { ' ' });
            
int idx = int.Parse(temp[0]);
            multi obj 
= new multi(idx);
            string[] res 
= obj.multiple();

            ListBox.Items.Clear();
            ListBox.Items.Add(ComboBox.Text);
            ListBox.Items.Add(
"");
            
for(int i = 0; i < res.Length; ++i)
                ListBox.Items.Add(res[i]);

        }


    }
}




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace mook_Gugudan
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }

        
private void cbbSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            
this.lbResult.Items.Clear();

            var s 
= this.cbbSelect.SelectedItem.ToString();
            var gustr 
= s.Split(new char[] { ' '
 });
           
           
            
this.lbResult.Items.Add(gustr[0] + "단 실행 결과");
            
this.lbResult.Items.Add("");
            
this.lbResult.Items.Add("");

            
for (var i = 1; i < 10; i++)
            {
                
this.lbResult.Items.Add(gustr[0] + " * " + i.ToString() + = " + (Convert.ToInt32(gustr[0]) * i).ToString());
            }
        }

      
    }
}



=SLIDERBOX


http://itsmart333.tistory.com/attachment/cfile29.uf@27626C37557E434F24D281.pdf


-FORM1




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SliderBox
{
    
public partial class Form1 : Form
    {
        
public static Point FormPt; // Form1위치
        public static Point FormPoint01; // From2 위치
        public static bool flag01;   // Form2가 열려 있는지를 판단
        public static bool flag02;  //From3이 열려 있는지를 판단
        public static bool flag03;  //Form3이 붙어 있는지를 판단

        Form2 frm2 = new Form2();
        Form3 frm3 
= new Form3();

        
public Form1()
        {
            InitializeComponent();
        }

        
private void Form1_LocationChanged(object sender, EventArgs e)
        {
            FormPt 
= this.Location;
            
if(flag01 == true)
            {
                frm2.Left 
= this.Left + 300;
                frm2.Top 
= this.Top + 30;
            }
            
else
            {
                frm2.Left 
= this.Left;
                frm2.Top 
= this.Top + 30;
            }
            
if(flag02 == true && flag03 == true)
            {
                frm3.Location 
= new Point(this.Location.X, this.Location.Y + 310);
            }
        }

        
private void btnShow_Click(object sender, EventArgs e)
        {
            
if(flag01 == false)
            {
                
this.btnShow.Text = "슬라이드 닫힘";
                FormPoint01.X 
= this.Location.X;
                FormPoint01.Y 
= this.Location.Y + 30;
                
this.TopMost = true;
                frm2.Visible 
= true;
                frm2.SlidingForm();
            }
            
else // 폼2가 열려 있을때 실행
            {
                
this.btnShow.Text = "슬라이드 열림";
                FormPoint01.X 
= this.Location.X + 300;
                FormPoint01.Y 
= this.Location.Y + 30;
                frm2.SlidingForm();
            }
        }

        
private void btnMsg_Click(object sender, EventArgs e)
        {
            
if(flag02 == false)
            {
                
this.btnMsg.Text = "폼 붙이기 닫기";
                frm3.Show();
                flag02 
= true;
                flag03 
= true;
                frm3.Location 
= new Point(this.Location.X, this.Location.Y + 310);
            }
            
else // 폼3이 열려 있을 때 실행
            {
                
this.btnMsg.Text = "폼 붙이기 열기";
                frm3.Hide();
                flag02 
= false;
                flag03 
= false;
            }
        }
    }
}


-FORM2




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SliderBox
{
    
public partial class Form2 : Form
    {
        
public Form2()
        {
            InitializeComponent();
        }

        
private void Form2_Load(object sender, EventArgs e)
        {
            SlidingForm();
        }

        
public void SlidingForm()
        {
            Location 
= Form1.FormPoint01;
            Timer.Start();
        }

        
private void timer_Tick(object sender, EventArgs e)
        {
            
if(Form1.flag01 == false)
            {
                Location 
= new Point(Location.X + 10, Location.Y);
                
if(Location.X == Form1.FormPoint01.X + 300)
                {
                    Timer.Stop();
                    Form1.flag01 
= true;
                }
            }
            
else
            {
                Location 
= new Point(Location.X - 10, Location.Y);
                
if (Location.X == Form1.FormPoint01.X - 300)
                {
                    Timer.Stop();
                    Form1.flag01 
= false;
                }
            }
        }
    }
}


-FORM3




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SliderBox
{
    
public partial class Form3 : Form
    {
        Point ptMouseCurrentPos; 
// 마우스 클릭 좌표 지정
        Point ptMouseNewPos;    // 이동시 마우스 좌표
        Point ptFormCurrentPos; // 폼 위치 좌표 지정
        Point ptFormNewPos; // 이동시 폼 위치 좌표
        bool bFormMouseDown = false;

        
public Form3()
        {
            InitializeComponent();
        }

        
private void Form3_MouseDown(object sender, MouseEventArgs e)
        {
            
if(e.Button == MouseButtons.Left)
            {
                bFormMouseDown 
= true;
                ptMouseCurrentPos 
= Control.MousePosition; // 마우스 클릭 좌표
                ptFormCurrentPos = this.Location;
            }
        }

        
private void Form3_MouseUp(object sender, MouseEventArgs e)
        {
            
if(e.Button == MouseButtons.Left)
            {
                bFormMouseDown 
= false;
                
if(this.Location.X <= Form1.FormPt.X + 30
                    && this.Location.X >= Form1.FormPt.X - 30)
                {
                    
if(this.Location.Y <= Form1.FormPt.Y + 340
                        && this.Location.Y >= Form1.FormPt.Y + 280)
                    {
                        
this.Location = new Point(Form1.FormPt.X, Form1.FormPt.Y + 310);
                        Form1.flag03 
= true;
                    }
                    
else
                    {
                        Form1.flag03 
= false;
                    }
                }
                
else
                {
                    Form1.flag03 
= false;
                }
            }
        }

        
private void Form3_MouseMove(object sender, MouseEventArgs e)
        {
            
if(bFormMouseDown == true)
            {
                ptMouseNewPos 
= Control.MousePosition;
                ptFormNewPos.X 
= ptMouseNewPos.X -
                    ptMouseCurrentPos.X + ptFormCurrentPos.X; 
// 마우스 이동시 가로 좌표
                ptFormNewPos.Y = ptMouseNewPos.Y -
                    ptMouseCurrentPos.Y + ptFormCurrentPos.Y; 
// 마우스 이동시 세로 좌표
                this.Location = ptFormNewPos;
                ptFormCurrentPos 
= ptFormNewPos;
                ptMouseCurrentPos 
= ptMouseNewPos;
            }
        }
    }
}



=

1.슬라이드 열림 클릭








-폼 붙이기 닫기 클릭





-FORM3 마우스로 드래그(설정된 FORM1의 범위안에 놓고 MOUSE UP 시 FORM1에 붙여짐)




=====앞으로 할 내용=====

==람다 + 링크(RAMBDA / LINQ)


=ADO.NET


-MSSQL

-MYSQL

-ACCESS


==네트워킹 처리 (스레드)

-소켓방식: 서로 다른 기종 간 통신

-TCP LISTENER



==========================================================================================

C++

==========================================================================================

<C++>



=상속


#include <iostream>
using namespace std;

class Coord
{
    
protected:
        
int x;
        
int
 y;
    
public:
        Coord(
int ax, int ay)
        {
            x 
= ax;
            y 
=
 ay;
        }

        
void GetXY(int &rx, int &ry)const
        {
            rx 
= x;
            ry 
= y;
        }
        
void SetXY(int ax, int ay)
        {
            x 
= ax;
            y 
= ay;
        }          
};

class Point : public Coord
{
    
protected:
        
char ch;
    
public:
        Point(
int ax, int ay, char ach) : Coord(ax,ay)
        {
            ch 
= ach;
        }
        
void Show()
        {
            cout 
<<"Show() - x: " << x << ", y: " <<  y << ", ch : " << ch << endl;
        }
        
void Hide()
        {
            cout 
<<"Hide() - x: " << x << ", y: " <<  y << ", ch : " << " " << endl;
        }
};

//상속 하지 않았을  경우////////////////////
/*
class Point : public Coord
{
    protected:
        int x;
        int y;

        char ch;
    public:
        Point(int ax, int ay, char ach) : Coord(ax,ay)
        {
            x 
= ax;
            y 
= ay;
            ch 
= ach;
        }
        void GetXY(int 
&rx, int &ry)const
        {
            rx 
= x;
            ry 
= y;
        }
        void SetXY(int ax, int ay)
        {
            x 
= ax;
            y 
= ay;
        }

          void Show()
        {
            cout 
<<"Show() - x: " << x << ", y: " <<  y << ", ch : " << ch << endl;
        }
        void Hide()
        {
            cout 
<<"Hide() - x: " << x << ", y: " <<  y << ", ch : " << " " << endl;
        }
};
*/
////////////////////////////////////////////////

int main()
{
    Point P(
10,10,'@');
    P.Show();
    P.Hide();

     return 0;
}






=상속과 정보 은폐

:부모의 private => 엑세스 불가

:부모의 protected => 엑세스 가능


#include <iostream>
#include <stdio.h>
using namespace std;

class B
{
    
private:
        
int b_pri;
        
void b_fpri()
        {
            puts(
"기반 클래스의 private 함수");
        }
    
protected:
        
int b_pro;
        
void b_fpro()
        {
            puts(
"기반 클래스의 protected 함수");
        }
    
public:
        
int b_pub;
        
void b_fpub()
        {
            puts(
"기반 클래스의 public 함수");
        }
};

class D : public B
{
    
private:
        
int d_pri;
        
void d_fpri()
        {
            puts(
"파생 클래스의 private 함수");
        }
    
public:
        
void d_fpub()
        {
            d_pri 
= 0;  //자신의 모든 멤버 액세스 가능
            d_fpri();

            b_pri = 1;  //에러 : 부모의 private 멤버는 액세스 불가
            b_fpri();

            b_pro 
= 2;  //부모의 protected 멤버는 액세스 가능
            b_fpro();

            b_pub 
= 3;  //부모의 public 멤버는 액세스 가능
            b_fpub();
        }
};

int main()
{
    D d;

    d.d_fpub(); 
//자신의 멤버함수 호출
    d.b_fpub(); 
//부모의 public 멤버함수 호출
    return 0;
}







= private부분 주석 처리


#include <iostream>
#include <stdio.h>
using namespace std;

class B
{
    
private:
        
int b_pri;
        
void b_fpri()
        {
            puts(
"기반 클래스의 private 함수");
        }
    
protected:
        
int b_pro;
        
void b_fpro()
        {
            puts(
"기반 클래스의 protected 함수");
        }
    
public:
        
int b_pub;
        
void b_fpub()
        {
            puts(
"기반 클래스의 public 함수");
        }
};

class D : public B
{
    
private:
        
int d_pri;
        
void d_fpri()
        {
            puts(
"파생 클래스의 private 함수");
        }
    
public:
        
void d_fpub()
        {
            d_pri 
= 0;  //자신의 모든 멤버 액세스 가능
            d_fpri();

            //b_pri = 1;  //에러 : 부모의 private 멤버는 액세스 불가
            //b_fpri();


            b_pro = 2;  //부모의 protected 멤버는 액세스 가능
            b_fpro();

            b_pub 
= 3;  //부모의 public 멤버는 액세스 가능
            b_fpub();
        }
};

int main()
{
    D d;

    d.d_fpub(); 
//자신의 멤버함수 호출
    d.b_fpub(); //부모의 public 멤버함수 호출
    return 0;
}








-gotoxy(x,y) 

#include <curses.h>

wmove(stdscr, y-1, x-1)

g++ -o main main.cc -lcurses

http://yumere.tistory.com/?page=41


=main() => class BMW : (   관문 1   ) CAR => calss CAR { (   관문 2   ):     

외부에서 접근시 관문 2개를 다 통과해야 부모(기반) 멤버 사용 가능



#include <iostream>
using namespace std;

class CAR
{
   
 private:       // 외부에서 호출시(main()) 관문 2
        int i_Pri;
    
protected:     // 외부에서 호출시(main()) 관문 2
        int i_Pro;
    
public:        // 외부에서 호출시(main()) 관문 2
        int i_Pub;

        CAR()
        {
            cout 
<< "CAR class가 생성되었습니다\n";
        }
        ~CAR()
        {
            cout 
<< "CAR class가 소멸되었습니다\n";
        }


};

//class BMW: CAR   // CAR : 외부에서 접근(main()) 관문 1 : private CAR ( DEFAULT )
class BMW:private CAR   // CAR : 외부에서 접근(main()) 관문 1 : private CAR ( DEFAULT )

//class BMW:protected CAR   // protected CAR : 파생 클래스의 인스턴스에서 사용 가능
//class BMW:protected CAR   // public CAR : 사용 가능
{
    
public:     //
        BMW()
        {
            cout 
<< "BMW class가 생성되었습니다\n";
        }
        ~BMW()
        {
            cout 
<< "BMW class가 소멸되었습니다\n";
        }
        
void f_Pri()
        {
         
   i_Pri = 100// CAR의 iPri;
        }
        
void f_Pro()
        {
            i_Pro 
= 100// CAR의 iPro;
        }
        
void f_Pub()
        {
            i_Pub 
= 100// CAR의 iPub;
        }

};



int main()
{
    BMW obj1;

    // 외부에서 CAR 멤버 접근
    obj1.f_Pri();
    obj1.f_Pro();
    obj1.f_Pub();

    
return 0;
}








==> 주석처리


#include <iostream>
using namespace std;

class CAR
{
    
private:       // 외부에서 호출시(main()) 관문 2
        int i_Pri;
    
protected:     // 외부에서 호출시(main()) 관문 2
        int i_Pro;
    
public:        // 외부에서 호출시(main()) 관문 2
        int i_Pub;
        CAR()
        {
            cout 
<< "CAR class가 생성되었습니다\n";
        }
        ~CAR()
        {
            cout 
<< "CAR class가 소멸되었습니다\n";
        }


};

//class BMW: CAR   // CAR : 외부에서 접근(main()) 관문 1 : private CAR ( DEFAULT )
class BMW:private CAR   // CAR : 외부에서 접근(main()) 관문 1 : private CAR ( DEFAULT )
//class BMW:protected CAR   // protected CAR : 파생 클래스의 인스턴스에서 사용 가능
//class BMW:public CAR   // public CAR : 사용 가능
{
    
public:     //
        BMW()
        {
            cout 
<< "BMW class가 생성되었습니다\n";
        }
        ~BMW()
        {
            cout 
<< "BMW class가 소멸되었습니다\n";
        }
        
void f_Pri()
        {
//            i_Pri = 100; // CAR의 iPri;
        }
        
void f_Pro()
        {
            i_Pro 
= 100// CAR의 iPro;
        }
        
void f_Pub()
        {
            i_Pub 
= 100// CAR의 iPub;
        }

};



int main()
{
    BMW obj1;

    
// 외부에서 CAR 멤버 접근
    obj1.f_Pri();
    obj1.f_Pro();
    obj1.f_Pub();

    
return 0;
}





=








=








=함수 오버 라이딩 ( 함수의 재정의)


#include <iostream>
using namespace std;

class CAR
{
    
public:
        CAR()
        {
            cout 
<< "CAR class가 생성되었습니다\n";
        }
        ~CAR()
        {
            cout 
<< "CAR class가 소멸되었습니다\n";
        }
  
      void Print()
        {
            cout 
<< "나는 CAR 입니다\n";
        }


};


class BMW:public CAR
{
    
public:
        BMW()
        {
            cout 
<< "BMW class가 생성되었습니다\n";
        }
        ~BMW()
        {
            cout 
<< "BMW class가 소멸되었습니다\n";
        }
        void Print() // 함수의 오버 라이딩
        {
            cout 
<< "나는 BMW 입니다\n";
        }


};



int main()
{
    BMW obj1;

    obj1.Print();       // BMW CLASS
    obj1.CAR::Print();  // CAR CLASS
    return 0;
}










=다중상속 ( 지원하는 언어 : C++ / CF - 단일상속 : 자바(대신 인터페이스 사용) )

class Z : public B, public C


#include <iostream>
#include <stdio.h>
using namespace std;

class Date
{
    
protected:
        
int year;
        
int month;
        
int day;
    
public:
        Date(
int y, int m, int d)
        {
            year 
= y;
            month 
= m;
            day 
= d;
        }
        
void OutDate()
        {
            cout 
<< year << "/" << month << "/" <<
 day;
        }

};

class Time
{
    
protected:
        
int hour;
        
int min;
        
int sec;
    
public:
        Time(
int h, int m, int s)
        {
            hour 
= h;
            min 
= m;
            sec 
= s;
        }
        
void OutTime()
        {
            cout 
<< hour << ":" << min << ":" <<
 sec;
        }

};

class Now : public Date, public Time // 다중 상속
{
    
private:
        
bool bEngMessage;
        
int milesec;
    
public:
        Now(
int y, int m ,int d, int h, int min, int s, int ms, bool b = false)
            :Date(y, m, d), Time(h, min, s)
        {
            milesec 
= ms;
            bEngMessage 
= b;
        }
        
void OutNow()
        {
            cout 
<< (bEngMessage ? "Now is ":"지금은 ");
            OutDate();
//            putch('');
            cout << " ";
            OutTime();
            cout 
<< "." << milesec;
            puts(bEngMessage ? 
".":" 입니다."
);
        }

};

int main()
{
    Now N(
20051212305899);
    N.OutNow();

    
return 0;
}








=다중상속의 문제점

:다이아몬드 계층도




'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150617  (0) 2015.06.17
20150616  (0) 2015.06.16
20150612  (0) 2015.06.14
20150611  (0) 2015.06.11
20150610  (0) 2015.06.10
Posted by ahj333
,

==========================================================================================

C#

==========================================================================================

<C#>


==델리게이트(Delegate) (: 메소드를 가리키는 객체)

class MainApp
{
  
public delegate void Mix(string s); // 델리게이트 선언(메소드에 대한 참조)-위임 / 대리자
 
  
public static void Coffee(string s)
  {
    Console.WriteLine(
"this Coffee is Mixed with {0} ", s);
  }
  
  
public static void CoCoa(string s)
  {
    Console.WriteLine(
"this CoCoa is Mixed with {0} ", s);
  }

  
public static void Main()
  {
    
Mix Tea = new Mix(Coffee); //할당된 델리게이트는 Coffee 메서드를 참조
    Tea("salt"); //Coffee 메서드를 참조하고 있으므로 Coffee("salt")를 실행
  
    
Tea = new Mix(CoCoa); //할당된 델리게이트는 CoCoa 메서드를 참조
    Tea("milk"); //Coffee 메서드를 참조하고 있으므로 CoCoa("milk")를 실행

  }
}




=왜 델리게이트를 사용하는가..

메소드 + 메소드 => 합성 불가

객체(인스턴스) + 객체(인스턴스) => 합성 가능


1. 델리게이트로 메소드를 객체로 만들어 합성 가능하도록


비엔나 : CALLBACK으로 이루어짐



using System;

class MainApp
{
  
public delegate void Stuff(); // 델리게이트 선언
 
  
public static void Sugar()
  {
    Console.WriteLine(
"Sugar");
  }
  
  
public static void Cream()
  {
    Console.WriteLine(
"Cream");
  }

  
public static void Milk()
  {
    Console.WriteLine(
"Milk");
  }

  
public static void Coffee()
  {
    Console.WriteLine(
"Coffee");
  }

  
public static void Main()
  {
    Stuff S = new Stuff(Sugar);
    Stuff C 
= new Stuff(Cream);
    Stuff M 
= new Stuff(Milk);
    Stuff cafe 
= new Stuff(Coffee);

    
    Console.WriteLine(
"비엔나 커피 만들기 : ");
    
Stuff Vienna = S + C + cafe; // 설탕 + 크림 + 커피 = 비엔나 커피   (Delegate의 합성)
    Vienna();
    Console.WriteLine();
      
    Console.WriteLine(
"까페오레 만들기 : ");
    
Stuff CafeAuLait = S + M + cafe; // 설탕 + 우유 + 커피 = 까페오레
    CafeAuLait();
    Console.WriteLine();

    Console.WriteLine(
"블랙커피 만들기 : ");
    
Stuff Black = CafeAuLait - M - S; // 커피 + 물 = 블랙커피
    Black();
  }
}





=CALLBACK : 이 코드가 실행할 세부코드는 컴파일 시점이 아닌 실행 시점에 부여함






=선언





2. 코드자체(로직)를 매개변수로 넘기려 할 때 사용 (:오름차순 /내림차순)


=일반화 델리게이트

using System;

namespace GenericDelegate
{
    
delegate int Compare<T>(T a, T b);
    
class Program
    {
        
static int AscendCompare<T>(T a, T b) where T : IComparable<T>
        {
            
return a.CompareTo(b);
        }


        
static int DescendCompare<T>(T a, T b) where T : IComparable<T>
        {
            
return a.CompareTo(b)*-1;
        }


        
static void BubbleSort<T>(T[] DataSet, Compare<T>Comparer)
        {
            
int i = 0;
            
int j = 0;
            T temp;

            
for(i = 0; i < DataSet.Length -1; ++i)
            {
                
for(j = 0; j < DataSet.Length-(i+1); ++j)
                {
                    
if(Comparer(DataSet[j], DataSet[j+1]) >0)
                    {
                        temp 
= DataSet[j+1];
                        DataSet[j+
1= DataSet[j];
                        DataSet[j] 
= temp;
                    }
                }
            }

        }

        
static void Main(string[] args)
        {
            
int[] array = { 374210 };
            Console.WriteLine(
"Sorting ascending...");
            
BubbleSort<int>(array, new Compare<int>(AscendCompare));

            
for (int i = 0; i < array.Length; ++i)
                Console.Write(
"{0} ", array[i]);

            string[] array2 
= { "abc""def""ghi""jkl""mno" };

            Console.WriteLine(
"\nSorting descending...");
            
BubbleSort<string>(array2, new Compare<string>(DescendCompare));

            
for (int i = 0; i < array2.Length; ++i)
                Console.Write(
"{0} ", array2[i]);

            Console.WriteLine();
        }
    }
}






=델리게이트 체인

... += ...;

... += ...;


=익명 메소드

:델리게이트 인스턴스 (한번만 실행하고 끝낼 것) ( 버블소트 : 익명메소드 사용)





using System;

namespace AnonymousMethod_2
{
    
delegate int Compare(int a, int b);
    
class Program
    {
        
/*
        static int AscendCompare
<T>(T a, T b) where T : IComparable<T>
        {
            return a.CompareTo(b);
        }

        static int DescendCompare
<T>(T a, T b) where T : IComparable<T>
        {
            return a.CompareTo(b) * -1;
        }
        */
        static void BubbleSort(int[] DataSet, Compare Comparer)
        {
            
int i = 0;
            
int j = 0;
            
int temp;

            
for (i = 0; i < DataSet.Length - 1; ++i)
            {
                
for (j = 0; j < DataSet.Length - (i + 1); ++j)
                {
                    
if (Comparer(DataSet[j], DataSet[j + 1]) > 0)
                    {
                        temp 
= DataSet[j + 1];
                        DataSet[j + 
1= DataSet[j];
                        DataSet[j] 
= temp;
                    }
                }
            }

        }
        
static void Main(string[] args)
        {
            
int[] array = { 374210 };
            Console.WriteLine(
"Sorting ascending...");

            
//BubbleSort<int>(array, new Compare<int>(AscendCompare));
            BubbleSort(array, delegate(int a, int b)
            {
                
if(a > b)
                    
return 1;
                
else if(a == b)
                    
return 0;
                
else
                    return -1;
            });


            
for (int i = 0; i < array.Length; ++i)
                Console.Write(
"{0} ", array[i]);

            
int[] array2 = {7281011};

            Console.WriteLine(
"\nSorting descending...");
            
//BubbleSort<string>(array2, new Compare<string>(DescendCompare));
            BubbleSort(array2, delegate(int a, int b)
            {
                
if (a < b)
                    
return 1;
                
else if (a == b)
                    
return 0;
                
else
                    return -1
;
            }
);



            
for (int i = 0; i < array2.Length; ++i)
                Console.Write(
"{0} ", array2[i]);

            Console.WriteLine();
        }
        
    }
}







=델리게이트와 이벤트(:더블클릭해서 코드 자동으로 뜨면 이렇게 동작하는 구나 ..알게됨)

-이벤트를 임의로 발생(테스트용도...)

-이벤트 : 객체에 일어난 사건(


-버튼1객체




-버튼1클릭 메소드

        private void button1_Click(object sender, EventArgs e)
        {

        }


:버튼 클릭 이벤트시 버튼1클릭 메소드를 붙임( 버튼 1 클릭시 버튼1클릭 메소드 실행 되도록)

            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(6432);
            
this.button1.Name = "button1";
            
this.button1.Size = new System.Drawing.Size(7523);
            
this.button1.TabIndex = 0;
            
this.button1.Text = "button1";
            
this.button1.UseVisualStyleBackColor = true;
   
         this.button1.Click += new System.EventHandler(this.button1_Click);






=


using System;

namespace DelegateEvent
{
    
class Client
    {
       
private int ID; 

       
public delegate void ClientService(object sender, EventArgs args);
       
//ClientService Service; // 델리게이트 선언
       public event ClientService Service; // 이벤트로 한정
   
       
public Client(int ID) // 생성자 : Client의 ID를 설정합니다.
       {
          
this.ID = ID;
       }

       
public int ClientID // ClientID 프로퍼티 : ID를 읽어옵니다.
       {
          get{ 
return this.ID; }
       }
 
       
public void FireEvent() // 이벤트를 발생시킵니다.
       {
          
if ( Service != null )
          {
             EventArgs args 
= new EventArgs(); // 마우스 클릭시 sender(어떤객체(버튼1/버튼2 클릭?),
       Service(this, args);                                     
//e(마우스가 클릭되었다) 생성
          }
       }
    }
    
class Program
    {
        
public static void OnEvent(object sender, EventArgs args)
        {
            Client client 
= (Client)sender;
            Console.WriteLine(
"고객번호 {0}, 경품 이벤트에 담청되셨습니다!.", client.ClientID);
        }


        
static void Main(string[] args)
        {
            Client clentA 
= new Client(1);
            
clentA.Service += new Client.ClientService(OnEvent);
            clentA.FireEvent();

            Client clentB 
= new Client(2);
            
clentB.Service += new Client.ClientService(OnEvent);
            clentB.FireEvent();

        }
    }
}








=구구단

2단

3단 

...뽑아 활용(index -X)


- 잘라내기


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace _20150612_1_MultiTable
{
          
    
class multi
    {
        
private int idan;

        
public multi(int id)
        {
            idan 
= id;
        }           
  
        
public string[] multiple()
        {
            string[] sone 
= new string[9];
            
int[] res = new int[9];
            
for(int i = 1; i < 10; ++i)
                sone[i-
1= idan + " * " + i + = " + ((idan)*i);
            
return sone;
        }
    }
    
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }

        
private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            string words 
= ComboBox.Text;
            string[] temp 
= words.Split(new Char[] { ' ' });
            
int idx = int.Parse(temp[0]);
            multi obj 
= new multi(idx);
            string[] res 
= obj.multiple();

            ListBox.Items.Clear();
            ListBox.Items.Add(ComboBox.Text);
            ListBox.Items.Add(
"");
            
for(int i = 0; i < res.Length; ++i)
                ListBox.Items.Add(res[i]);

        }


    }
}





==========================================================================================

C++

==========================================================================================

<C++>


=car1.print(&cout);

*T

*T : cout



#include <iostream>
#include <string.h>
using namespace std;

class CAR
{
    
private:
        
int iColor;
        
int iSpeed;
        
char *cName;
        
void CarName(const char *);
    
public:
        CAR();
        CAR(
const char *);
        CAR(
const CAR &);
        ~CAR();
        
void SetColor(const int);
        
void SetSpeed(const int);
        
void SetName(const char *);
       
 void Print(ostream *);
        
const CAR operator=(const CAR &); // 연산자 재정의
        void operator+=(const CAR &);        
};


void CAR::CarName(const char * T)
{
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen(T)+1];
    strcpy(cName, T);
#ifdef DEBUG // DEBUG
    cout << cName << "이 생성 되었습니다\n";
#endif
}

CAR::CAR()
{
    CarName(
"car");
    
/*
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen("car")+1];
    strcpy(cName,"car");
    cout 
<< cName << "이 생성 되었습니다\n";*/
}

CAR::CAR(
const char * T)
{
    CarName(T);
    
/*
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen(T)+1];
    strcpy(cName, T);
    cout 
<< cName << "이 생성 되었습니다\n";*/
}

CAR::CAR(
const CAR & A)
{
    iColor 
= A.iColor;
    iSpeed 
= A.iSpeed;
    cName 
= new char[strlen(A.cName)+1];
    strcpy(cName, A.cName);

#ifdef DEBUG // DEBUG
    cout << cName << "이 복사 생성 되었습니다\n";
#endif
}

CAR::~CAR()
{
#ifdef DEBUG // DEBUG
    cout << cName << "이 소멸 되었습니다\n";
#endif
    delete [] cName;
}

void CAR::SetColor(const int ic)
{
    iColor 
= ic;
#ifdef DEBUG // DEBUG
    cout << cName << " Color : " << iColor << " 로 변경 되었습니다\n";
#endif
}

void CAR::SetSpeed(const int is)
{
    iSpeed 
= is;
#ifdef DEBUG // DEBUG
    cout << cName << " Speed : " << iSpeed << " 로 변경 되었습니다\n";
#endif
}

void CAR::SetName(const char * cn)
{
#ifdef DEBUG // DEBUG
    cout << cName << " Name  : ";
#endif
    delete [] cName;
    cName 
= new char[strlen(cn)+1];
    strcpy(cName, cn);    
#ifdef DEBUG // DEBUG
    cout << cName << " 로 변경 되었습니다\n";
#endif
}

const CAR CAR::operator=(const CAR & T) // 연산자 재정의
{
    
//iColor = T.iColor;
    //iSpeed = T.Speed;
#ifdef DEBUG // DEBUG
    cout << "operator=\n";
#endif
    SetColor(T.iColor); // 인라인으로 하면 좋음
    SetSpeed(T.iColor);
    SetName(T.cName);
#ifdef DEBUG // DEBUG
    cout << "====================\n";
#endif
    return *this;
}

void CAR::operator+=(const CAR & T)
{
#ifndef DEBUG
    cout 
<< cName << "+=" << T.cName << endl;
#endif
    iColor = iColor + T.iColor;
    iSpeed 
= iSpeed + T.iSpeed;
    
char * temp = new char[strlen(cName) + strlen(T.cName) + 1];
    strcpy(temp, cName);
    strcat(temp, T.cName);
    
delete [] cName;
    cName 
= temp;
#ifndef DEBUG
    cout 
<< ": " <<  cName << endl;
#endif
}

void CAR::Print(ostream * T) // iostream = istream + ostream
{
    *T 
<< "CAR {" << iColor << "," << iSpeed << "," << cName << "}";
}


int main()
{
    CAR car1;
    CAR car2(
"BMW");
    CAR car3(
"내꺼");
//    car3 = car2 = car1;
    car1+=car2;
    car3.Print(
&cout);
    
return 0;
}




= << 연산자


-다른 클래스의 소속 cout


A+B => operator+(&A,&B) => operator+(&B) : 가능 (CLASS내에 선언 가능 : 인자 1개)


cout << Car3

-cout: class에 못들어감 => 전역 으로만 만들 수 있음 (인자 2개)


cout << 3 << 4 << 5 << endl;

연산 방향 : 왼쪽 -> 오른쪽


cout << 3 : 3출력 => cout 남음(ostream) 값 ( &) => ostream & : 반환형

cout << 4 => cout << 5 => cout << endl


ostream & operator<<( ostream & ,CAR  &)


#include <iostream>
#include <string.h>
using namespace std;

class CAR
{
    
private:
        
int iColor;
        
int iSpeed;
        
char *cName;
        
void CarName(const char *);
    
public:
        CAR();
        CAR(
const char *);
        CAR(
const CAR &);
        ~CAR();
        
void SetColor(const int);
        
void SetSpeed(const int);
        
void SetName(const char *);
        
void Print(ostream *);
        
const CAR operator=(const CAR &); // 연산자 재정의
        void operator+=(const CAR &);        
};


void CAR::CarName(const char * T)
{
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen(T)+1];
    strcpy(cName, T);
#ifdef DEBUG // DEBUG
    cout << cName << "이 생성 되었습니다\n";
#endif
}

CAR::CAR()
{
    CarName(
"car");
    
/*
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen("car")+1];
    strcpy(cName,"car");
    cout 
<< cName << "이 생성 되었습니다\n";*/
}

CAR::CAR(
const char * T)
{
    CarName(T);
    
/*
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen(T)+1];
    strcpy(cName, T);
    cout 
<< cName << "이 생성 되었습니다\n";*/
}

CAR::CAR(
const CAR & A)
{
    iColor 
= A.iColor;
    iSpeed 
= A.iSpeed;
    cName 
= new char[strlen(A.cName)+1];
    strcpy(cName, A.cName);

#ifdef DEBUG // DEBUG
    cout << cName << "이 복사 생성 되었습니다\n";
#endif
}

CAR::~CAR()
{
#ifdef DEBUG // DEBUG
    cout << cName << "이 소멸 되었습니다\n";
#endif
    delete [] cName;
}

void CAR::SetColor(const int ic)
{
    iColor 
= ic;
#ifdef DEBUG // DEBUG
    cout << cName << " Color : " << iColor << " 로 변경 되었습니다\n";
#endif
}

void CAR::SetSpeed(const int is)
{
    iSpeed 
= is;
#ifdef DEBUG // DEBUG
    cout << cName << " Speed : " << iSpeed << " 로 변경 되었습니다\n";
#endif
}

void CAR::SetName(const char * cn)
{
#ifdef DEBUG // DEBUG
    cout << cName << " Name  : ";
#endif
    delete [] cName;
    cName 
= new char[strlen(cn)+1];
    strcpy(cName, cn);    
#ifdef DEBUG // DEBUG
    cout << cName << " 로 변경 되었습니다\n";
#endif
}

const CAR CAR::operator=(const CAR & T) // 연산자 재정의
{
    
//iColor = T.iColor;
    //iSpeed = T.Speed;
#ifdef DEBUG // DEBUG
    cout << "operator=\n";
#endif
    SetColor(T.iColor); // 인라인으로 하면 좋음
    SetSpeed(T.iColor);
    SetName(T.cName);
#ifdef DEBUG // DEBUG
    cout << "====================\n";
#endif
    return *this;
}

void CAR::operator+=(const CAR & T)
{
#ifndef DEBUG
    cout 
<< cName << "+=" << T.cName << endl;
#endif
    iColor = iColor + T.iColor;
    iSpeed 
= iSpeed + T.iSpeed;
    
char * temp = new char[strlen(cName) + strlen(T.cName) + 1];
    strcpy(temp, cName);
    strcat(temp, T.cName);
    
delete [] cName;
    cName 
= temp;
#ifndef DEBUG
    cout 
<< ": " <<  cName << endl;
#endif
}

void CAR::Print(ostream * T) // iostream = istream + ostream
{
    *T 
<< "CAR {" << iColor << "," << iSpeed << "," << cName << "}";
}


ostream & operator<<(ostream & O, CAR & T)
{
    T.Print(
&O); //객체 출력
    return
 O;
}


int main()
{
    CAR car1;
    CAR car2(
"BMW");
    CAR car3(
"내꺼");
//    car3 = car2 = car1;
    car1+=car2;
//    car3.Print(&cout);
    cout << car3 << endl;
    
return 0;
}






=객체의 배열

Point arr[3] = { Point(100, 100), Point(50, 100), Point( 10, 10) };




=포함 

구조체 속 구조체

클래스 속 클래스..


==CIN


=

#include <iostream>
using namespace std;



int main()
{
    
char cNum;
    
int iNum;
    
float fNum;

    cin 
>> cNum;
    cout 
<< cNum << endl;

    
return 0;
}





=


#include <iostream>
using namespace std;



int main()
{
    
char cNum;
    
int iNum;
    
float fNum;

    cin 
>> cNum;
    cout 
<< (int)cNum << endl;

    
return 0;
}





=

#include <iostream>
using namespace std;



int main()
{
    
char cNum;
    
int iNum;
    
float fNum;

//    cin >> cNum;
//    cout 
<< (int)cNum << endl;

    cin >> fNum;
    cout 
<< fNum << endl;


    
return 0;
}





=

#include <iostream>
using namespace std;



int main()
{
    
char cNum;
    
int iNum;
    
float fNum;

//    cin >> cNum;
//    cout 
<< (int)cNum << endl;

//    cin 
>> fNum;
//    cout 
<< fNum << endl;

    char buf[200];
    cin 
>>
 buf;
    cout 
<< buf << endl;
    
return 0;
}





= : 상속 ( 자바 : extens)


class BMW : CAR






#include <iostream>
using namespace std;

class CAR
{
    
public:
        CAR()
        {
            cout 
<< "CAR class가 생성되었습니다\n";
        }
        ~CAR()
        {
            cout 
<< "CAR class가 소멸되었습니다\n";
        }


};

class BMW:CAR
{
    
public:
        BMW()
        {
            cout 
<< "BMW class가 생성되었습니다\n";
        }
        ~BMW()
        {
            cout 
<< "BMW class가 소멸되었습니다\n";
        }

};



int main()
{
    BMW obj1;
    
return 0;
}







'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150616  (0) 2015.06.16
20150615  (0) 2015.06.16
20150611  (0) 2015.06.11
20150610  (0) 2015.06.10
20150609  (0) 2015.06.09
Posted by ahj333
,

==========================================================================================

C#

==========================================================================================


<C#>


-p617

=CONSOL APP

-consol에서 window form 띄우기/버튼추가/이벤트추가







=상속 받기

     class MainApp:Form //:System.Windows.Forms.Form 상속(window form) - 길어서 using 추가
    {
        
static void Main(string[] args)
        {

        }
    }



=windows form 생성/ 구동


     class MainApp:Form //:System.Windows.Forms.Form 상속(window form) - 길어서 using 추가
    {
        
static void Main(string[] args)
        {
            MainApp form 
= new MainApp();

            Application.Run(form); 
//
            //Application.Run(new MainApp()); // book p 617

        }
    }


=버튼1 생성 -  버튼1 text 입력 / 버튼1 추가

     class MainApp:Form //:System.Windows.Forms.Form 상속(window form) - 길어서 using 추가
    {
        
static void Main(string[] args)
        {
            MainApp form 
= new MainApp();

            Button button1 
= new Button();
            button1.Text 
= "button1"
;
            form.Controls.Add(button1);


            Application.Run(form); 
//
            //Application.Run(new MainApp()); // book p 617

        }
    }





=버튼2 생성 - 버튼2 text 입력 / 버튼2위치 변경 / 버튼2 text 추가

     class MainApp:Form //:System.Windows.Forms.Form 상속(window form) - 길어서 using 추가
    {
        
static void Main(string[] args)
        {
            MainApp form 
= new MainApp();

            Button button1 
= new Button();
            button1.Text 
= "button1";
            form.Controls.Add(button1);

            Button button2 
= new Button();
            button2.Text 
= "button2";
            button2.Left 
= 200
;
            form.Controls.Add(button2);


            Application.Run(form); 
//
            //Application.Run(new MainApp()); // book p 617

        }
    }








=이벤트 핸들러 -

-선택시 자동 코드 생성됨





-동작할 내용 코딩





         private static void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show(sender.ToString());
            MessageBox.Show(e.ToString());

        }







        static void button2_Click(object sender, EventArgs e)
        {
            
throw new NotImplementedException();
        }


-ALT-F5


-CTRL-F5




==============================================================================================

=WINDOWS FORM APP


=델리게이트 => 이벤트객체에 메소드객체(메소드 객체의 위임 객체)를 붙임





=원래 한곳에 모여 있었으나 코딩 라인이 길어 목적에 맞게 나눔 => partial class














=종료






=OS가 APP메세지 전달 = 메시지 가로채기( 내용 바꿀수 있음 )

-우클릭 => 좌클릭 / NULL


=메세지 필터

: IMessageFilter // 인터페이스 상속



=예제 P643













        private void Form1_Load(object sender, EventArgs e)
        {

        }

        
private void cboFont_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        
private void chkBold_CheckedChanged(object sender, EventArgs e)
        {

        }

        
private void chkItalic_CheckedChanged(object sender, EventArgs e)
        {

        }


=

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace wintest1
{
    
public partial class Form1 : Form
    {
        
public Form1()
        {
            InitializeComponent();
        }

        
void ChangeFont()
        {
            
if (cboFont.SelectedIndex < 0)
                
return;

            FontStyle style 
= FontStyle.Regular;

            
if (chkBold.Checked)
                style 
|= FontStyle.Bold;

            
if (chkItalic.Checked)
                style 
|= FontStyle.Italic;

            txtSampleText.Font 
= new Font((string)cboFont.SelectedItem, 10, style);
        }

        
private void Form1_Load(object sender, EventArgs e)
        {
            var Fonts 
= FontFamily.Families;
            foreach (FontFamily font in Fonts)
                cboFont.Items.Add(font.Name);
        }

        
private void cboFont_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeFont();
        }

        
private void chkBold_CheckedChanged(object sender, EventArgs e)
        {
            ChangeFont();
        }

        
private void chkItalic_CheckedChanged(object sender, EventArgs e)
        {
            ChangeFont();
        }
        
    }
}







=이벤트구동형 ( Event Driven Pro...)

:순서 의미 없음





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace wintest1
{
    
public partial class Form1 : Form
    {
        Random random 
= new Random(37);
        
public Form1()
        {
            InitializeComponent();

            lvDummy.Columns.Add(
"Name");
            lvDummy.Columns.Add(
"Depth");
        }

        
void ChangeFont()
        {
            
if (cboFont.SelectedIndex < 0)
                
return;

            FontStyle style 
= FontStyle.Regular;

            
if (chkBold.Checked)
                style 
|= FontStyle.Bold;

            
if (chkItalic.Checked)
                style 
|= FontStyle.Italic;

            txtSampleText.Font 
= new Font((string)cboFont.SelectedItem, 10, style);
        }

        
private void Form1_Load(object sender, EventArgs e) // Font 가져옴
        {
            var Fonts 
= FontFamily.Families;
            foreach (FontFamily font in Fonts)
                cboFont.Items.Add(font.Name);
        }

        
private void cboFont_SelectedIndexChanged(object sender, EventArgs e) // 
        {
            ChangeFont();
        }

        
private void chkBold_CheckedChanged(object sender, EventArgs e)
        {
            ChangeFont();
        }

        
private void chkItalic_CheckedChanged(object sender, EventArgs e)
        {
            ChangeFont();
        }

        
private void tbDummy_Scroll(object sender, EventArgs e)
        {
            pgDummy.Value 
= tbDummy.Value;
        }

        
private void btnModal_Click(object sender, EventArgs e)
        {
            Form frm 
= new Form();
            frm.Text 
= "Modal Form";
            frm.Width 
= 300;
            frm.Height 
= 100;
            frm.BackColor 
= Color.Red;
            frm.ShowDialog();
        }

        
private void btnModaless_Click(object sender, EventArgs e)
        {
            Form frm 
= new Form();
            frm.Text 
= "Modaless Form";
            frm.Width 
= 300;
            frm.Height 
= 300;
            frm.BackColor 
= Color.Green;
            frm.ShowDialog();
        }

        
private void btnMsgBox_Click(object sender, EventArgs e)
        {
            MessageBox.Show(txtSampleText.Text, 
"MessageBox Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        
        
void TreeToList()
        {
            lvDummy.Items.Clear();
            foreach (TreeNode node in tvDummy.Nodes)
                TreeToList(node);
        }

        
void TreeToList(TreeNode Node)
        {
            lvDummy.Items.Add(
                
new ListViewItem(new string[] { Node.Text, Node.FullPath.Count(f => f == '\\').ToString() }));

            foreach(TreeNode node in Node.Nodes)
            {
                TreeToList(node);
            }
        }

        
private void btnAddRoot_Click(object sender, EventArgs e)
        {
            tvDummy.Nodes.Add(random.Next().ToString());
            TreeToList();
        }

        
private void btnAddChild_Click(object sender, EventArgs e)
        {
            
if(tvDummy.SelectedNode == null)
            {
                MessageBox.Show(
"선택된 노드가 없습니다.",
                    
"TreeView Test", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
return;
            }
            tvDummy.SelectedNode.Nodes.Add(random.Next().ToString());
            tvDummy.SelectedNode.Expand();
            TreeToList();
        }
        
    }
}
















==========================================================================================

C++

==========================================================================================

<C++>


=

C책 P387

http://itsmart333.tistory.com/186


int *A = new int[3];

delete []A;

int **B = new int*[3];

delete []B;

int *A = &B;


int (*C)[3] = new int[2][3]

delete []C;



#include <iostream>
using namespace std;

int main(void)
{
  
int arr[2][2][2=  { 
              {  { 
12 },
                { 
34 } },

              {  { 
56 },
                { 
78 } }
            };
  printf(
"%d \n", arr[0][0][1]);
  printf(
"%d \n", *(*(*(arr + 1) + 0) + 1));
  printf(
"%d \n", (*(arr + 1))[0][1]);
  printf(
"%d \n", (*(*(arr + 1) + 0))[1]);
  printf(
"%d \n", *(*(arr[1] + 0) + 1));
  printf(
"%d \n", (*(arr[1] + 0))[1]);
  printf(
"%d \n", *(arr[1][0] + 1));

  
int *A = new int[3];
  
int **B = new int*[3];
  
int(*C)[3= new int[2][3];

  cout 
<< C << endl;
  cout 
<< C + 1 << endl;
  cout 
<< ((C + 1) - C) / 0x04 << endl;
  cout 
<< sizeof(int<< endl;
  cout 
<< sizeof(*C) << endl;
  cout 
<< sizeof(C) << endl;
  cout 
<< sizeof(**C) << endl;
  cout 
<< sizeof((*C)[3]) << endl;

  cout 
<< sizeof(C[0][0]) << endl;

  
for (int i = 0; i < 2; ++i) //sizeof(*(C[3]))
    for (int j = 0; j < sizeof(*C)/sizeof(**C); ++j)
      C[i][j] 
= (i + 1)*(j + 1);

  
for (int i = 0; i < 2; ++i)
    
for (int j = 0; j < sizeof(*C)/sizeof(**C); ++j)
      cout 
<< C[i][j] << endl;

  
delete[]C;


  
return 0;
}






=car class 코딩하기




=car class


#include <iostream>
#include <string.h>
using namespace std;

class CAR
{

    
private:
        
int iColor;
        
int iSpeed;
        
char *cName;
        
void CarName(const char *);
    
public:
        CAR();
        CAR(
const char *);
        CAR(
const CAR &);
        ~CAR();
        
void SetColor(const int);
        
void SetSpeed(const int);
        
void SetName(const char *);
        
void Print(ostream *IN);
         void 
CAR operator (CAR &); // 연산자 재정의
        void operator+=(CAR &IN);        
};


void CAR::CarName(const char * T)
{
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen(T)+1];
    strcpy(cName, T);

    cout << cName << "이 생성 되었습니다\n";

}

CAR::CAR()
{
    CarName(
"car");
    
/*
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen("car")+1];
    strcpy(cName,"car");
    cout 
<< cName << "이 생성 되었습니다\n";*/
}

CAR::CAR(
const char * T)
{
    CarName(T);
    
/*
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen(T)+1];
    strcpy(cName, T);
    cout 
<< cName << "이 생성 되었습니다\n";*/
}

CAR::CAR(
const CAR & A)
{
    iColor 
= A.iColor;
    iSpeed 
= A.iSpeed;
    cName 
= new char[strlen(A.cName)+1];
    strcpy(cName, A.cName);


    cout << cName << "이 복사 생성 되었습니다\n";

}

CAR::~CAR()
{

    cout << cName << "이 소멸 되었습니다\n";

    delete [] cName;
}

void CAR::SetColor(const int ic)
{
    iColor 
= ic;

    cout << cName << " Color : " << iColor << " 로 변경 되었습니다\n";

}

void CAR::SetSpeed(const int is)
{
    iSpeed 
= is;

    cout << cName << " Speed : " << iSpeed << " 로 변경 되었습니다\n";

}

void CAR::SetName(const char * cn)
{

    cout << cName << " Name  : ";

    delete [] cName;
    cName 
= new char[strlen(cn)+1];
    strcpy(cName, cn);    

    cout << cName << " 로 변경 되었습니다\n";

}

//void Print(ostream *IN);
void CAR::operator=(const CAR & T) // 연산자 재정의
{
    
//iColor = T.iColor;
    //iSpeed = T.Speed;

    cout << "operator=\n";

    SetColor(T.iColor); // 인라인으로 하면 좋음
    SetSpeed(T.iColor);
    SetName(T.cName);
    
}
//void operator+=(CAR &IN);        

int main()
{
    CAR obj1;
    CAR obj2
=obj1;

    obj1.SetName(
"ca1");
    obj1.SetColor(
1);
    obj1.SetSpeed(
10);

    obj2.SetName(
"ca2");
    obj2.SetColor(
2);
    obj2.SetSpeed(
20);

    
return 0;
}









=CAR3 = CAR2 = CAR1

CAR2 = CAR1 ====> void형 남음

CAR3 = void  ====> ERROR


void CAR::operator=(const CAR & T) // 연산자 재정의
{
    
//iColor = T.iColor;
    //iSpeed = T.Speed;

    cout << "operator=\n";

    SetColor(T.iColor); // 인라인으로 하면 좋음
    SetSpeed(T.iColor);
    SetName(T.cName);

    cout << "====================\n";


}


===============>> const CAR 반환하도록 변경필요









=void => const CAR로 변경

CAR2 = CAR1



CAR3 = CAR2 = CAR1 => return *this시 임시객체 생성 : 복사생성자 호출 ( = 연산자 2번 호출 되므로 복사생성 2번 됨)


const CAR CAR::operator=(const CAR & T) // 연산자 재정의
{
    
//iColor = T.iColor;
    //iSpeed = T.Speed;

    cout << "operator=\n";

    SetColor(T.iColor); // 인라인으로 하면 좋음
    SetSpeed(T.iColor);
    SetName(T.cName);

    cout << "====================\n";

    return *this;
}











= C개념 추가(출력 ON/OFF)

#define DEBUG

cout << ...

#endif


-DDUBUG



#include <iostream>
#include <string.h>
using namespace std;

class CAR
{
    
private:
        
int iColor;
        
int iSpeed;
        
char *cName;
        
void CarName(const char *);
    
public:
        CAR();
        CAR(
const char *);
        CAR(
const CAR &);
        ~CAR();
        
void SetColor(const int);
        
void SetSpeed(const int);
        
void SetName(const char *);
        
void Print(ostream *IN);
        
const CAR operator=(const CAR &); // 연산자 재정의
        void operator+=(CAR &IN);        
};


void CAR::CarName(const char * T)
{
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen(T)+1];
    strcpy(cName, T);
#ifdef DEBUG // DEBUG
    cout << cName << "이 생성 되었습니다\n";
#endif
}

CAR::CAR()
{
    CarName(
"car");
    
/*
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen("car")+1];
    strcpy(cName,"car");
    cout 
<< cName << "이 생성 되었습니다\n";*/
}

CAR::CAR(
const char * T)
{
    CarName(T);
    
/*
    iColor 
= 0;
    iSpeed 
= 0;
    cName 
= new char[strlen(T)+1];
    strcpy(cName, T);
    cout 
<< cName << "이 생성 되었습니다\n";*/
}

CAR::CAR(
const CAR & A)
{
    iColor 
= A.iColor;
    iSpeed 
= A.iSpeed;
    cName 
= new char[strlen(A.cName)+1];
    strcpy(cName, A.cName);

#ifdef DEBUG // DEBUG
    cout << cName << "이 복사 생성 되었습니다\n";
#endif
}

CAR::~CAR()
{
#ifdef DEBUG // DEBUG
    cout << cName << "이 소멸 되었습니다\n";
#endif
    delete [] cName;
}

void CAR::SetColor(const int ic)
{
    iColor 
= ic;
#ifdef DEBUG // DEBUG
    cout << cName << " Color : " << iColor << " 로 변경 되었습니다\n";
#endif
}

void CAR::SetSpeed(const int is)
{
    iSpeed 
= is;
#ifdef DEBUG // DEBUG
    cout << cName << " Speed : " << iSpeed << " 로 변경 되었습니다\n";
#endif
}

void CAR::SetName(const char * cn)
{
#ifdef DEBUG // DEBUG
    cout << cName << " Name  : ";
#endif
    delete [] cName;
    cName 
= new char[strlen(cn)+1];
    strcpy(cName, cn);    
#ifdef DEBUG // DEBUG
    cout << cName << " 로 변경 되었습니다\n";
#endif
}

//void Print(ostream *IN);
const CAR CAR::operator=(const CAR & T) // 연산자 재정의
{
    
//iColor = T.iColor;
    //iSpeed = T.Speed;
#ifdef DEBUG // DEBUG
    cout << "operator=\n";
#endif
    SetColor(T.iColor); // 인라인으로 하면 좋음
    SetSpeed(T.iColor);
    SetName(T.cName);
#ifdef DEBUG // DEBUG
    cout << "====================\n";
#endif
    return *this;
}
//void operator+=(CAR &IN);        
int main()
{
    CAR car1;
    CAR car2(
"BMW");
    CAR car3(
"내꺼");
    car3 
= car2 = car1;
    
return 0;
}
/*
int main()
{
    CAR obj1;
    CAR obj2
=obj1;

    obj1.SetName("ca1");
    obj1.SetColor(1);
    obj1.SetSpeed(10);

    obj2.SetName("ca2");
    obj2.SetColor(2);
    obj2.SetSpeed(20);

    return 0;
}*/






'2015 스마트 콘트롤러 > 업무일지' 카테고리의 다른 글

20150615  (0) 2015.06.16
20150612  (0) 2015.06.14
20150610  (0) 2015.06.10
20150609  (0) 2015.06.09
20150608  (0) 2015.06.09
Posted by ahj333
,