1 / 20

A Basic of C++

A Basic of C++. Basic Structure of C++. /* c++ 파일 확장명 filename: Hello.cpp */ #include&lt;iostream.h&gt; void main() { cout&lt;&lt; “ Hello world <br> ” ; } 프로그램이 처음 시작할 때 자동으로 호출 된다. 함수 프로그램구조 순서 1.#inclue&lt;iostream.h&gt; 2. 원형함수 3.main() 함수 4. 정의 함수 #include&lt;iostream.h&gt;

cwen
Download Presentation

A Basic of C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A Basic of C++

  2. Basic Structure of C++ /* c++파일 확장명 filename: Hello.cpp */ #include<iostream.h> void main() { cout<<“Hello world \n”; } 프로그램이 처음 시작할 때 자동으로 호출 된다 함수 프로그램구조 순서 1.#inclue<iostream.h> 2.원형함수 3.main()함수 4.정의 함수 #include<iostream.h> int FindArea(int x); // 원형 함수 void main() { 변수 지정; // int a=10; 함수 호출; // FindArea(10); } int FindArea(int x) // 정의 함수 { 문장내용 retrurn반환 값; }

  3. Variable 변수란 : 정보를 저장하는 장소이며, 값들을 저장하고 그 값들을 검색하는 컴퓨터의 메모리의 특정 위치이다. unsigned :항상 양수를 갖는다. signed : unsigned 가 붙지 않은 정수형으로 음수 및 양수를 가질 수 있다.

  4. The Basis of Class 1. 클래스란 : 관련된 함수들과 연관된 변수들의 집합입니다. 클래스 선언: class, 클래스 명 중괄호( ; ) 클래스 문장구조: class Cat { public: // 범용 접근 제한자 unsigned int itsAge; unsigned int itsWeight; Cat(); // 생성자 ~Cat(); // 소멸자 void Meow(); // 클래스 메소드 private: // 전용접근 제한자 }; 객체의 정의: 1. 정수형을 정의하는 것과 같다 2. 클래스명 과 객체변수를 써준다. <정수형 정의> Unsigned int GrooWeight; int Age; double Age; <객체의 정의> Cat Frisky ; Dog Jindo ;

  5. The Basis of Class 2. 클래스 멤버의 접근: 점 연산자(.)를 사용하여 접근 클래스변수 접근 Frisky.Weight =50; 클래스 메소드 접근 Frisky.Meow(); private: // 전용 접근 제한자 모든 클래스의 멤버는 private로 선언 되어있다 클래스 안의 메소드들에 의해서만 접근 된다 public: // 범용 접근 제한자 다른 클래스 객체에서 접근 가능하다 Class Cat { public: // 범용 접근 제한자 unsigned int GetAge(); void SetAge(unsigned int Age); unsigned int GetWeight(); void SetWeight(unsigned int Weight); private: // 전용 접근 전한자 unsigned int itsAge; unsigned int itsWeight; };

  6. The Basis of Class 3. 클래스 메소드 구현: 반환 값 을 쓰고 클래스 이름 두개의 콜론(::)을 넣고 함수명을 쓴 뒤 매개변수를 씁니다 // <int 형 반환 값을 가지는 메소드> int Cat::GetAge() { return itsAge; } // <void 형 반환 값을 가지는 메소드> void Cat::Meow() { cout<<“Meox.\n”; } 생성자: 멤버자료를 초기화 해준다. 반환 값 과 void 형이 없다 클래스 이름과 같다. Cat::Cat(int initial) { itsAge = initial; } 소멸자: 생성자를 선언할 때 소멸자를 만들어야 합니다. Cat::~Cat() { cout<<“deconstructor”; }

  7. The Basis of Class 4. #include<iostream.h> Class Cat { private: // 전용 접근 제한자 int itsAge; public: // 범용 접근 제한자 Cat(int initaialAge); ~Cat(); int GetAge(){return itsAge;} // inline void SetAge(int age); void Meow(){cout<<“Meow”;} }; Cat::Cat(int initalAge) // 생성자 { itsAge= initialAge; } Cat::~Cat() //소멸자 { } Cat::SetAge(int age) // 클래스 메소드 { itsAge = age; } void main() { Cat Frisky(5);// 객체를 생성, 생성자 함수 호출 Frisky.Meow(); //객체의 함수호출 cout<<“Frisky is a cat who is “; cout<<Frisky.GetAge()<<“year”; Frisky.Mewo(); Frisky.SetAge(7); cout<<“Now Frisky is”; cout<<Frisk.GetAge()<<“Year”; }

  8. Pointer 포인터란:메모리의 주소를 가리킬 수 있는 수 있는 변수 변수 앞에 *를 붙여줍니다. 간접지정연산자 (*): 포인터가 조회되었을 때 그 포인터 에 저장된 주소에 있는 값이 검색 주소연산자(&): 컴퓨터 메모리의 주소 자유기억공간할당: new라는 예약어를 통해 자유 기억 공간에 메모리를 할당할 수 있다. New로부터 반환 되는 것은 메모리의 주소이다 unsigned short int howOld =50; 변수 howOld, unsigned short 정수형 값을 50으로 초기화 하였습니다 unsigned short int *pAge=0; pAge를 unsigned short 정수형의 포인터로 선언하고 초기화 하였습니다. pAge = &howOld; howOld의 주소를 pAge에 저장하였습니다 unsigned short int howOld=50; unsigned short int *pAge = &howOld; unsigned short int *pPointer; pPointer = new unsigned short int; Animal *pDag = new Animal;

  9. Pointer Example #inclue<iostream.h> class SimpleCat {private: // 전용접근 제한자 int *itsAge; //정수형 포인터 int *itsWeight; public: // 범용접근 제한자 SimpleCat(); // 생성자 ~SimpleCat();// 소멸자 int GetAge()const{return *itsAge;} void SetAge(int age); int GetWeight( )const; }; SimpleCat::SimpleCat() { itsAge = new int(2); itsWeight= new int(5); } SimpleCat::~SimpleCat() { delete itsAge; delete itsWeight; } SimpleCat::SetAge(int age) { *itsAge = age; //포인터에 age를 할당한다. } SimpleCat::GetWeight()const { return *itsWeight; //포인터를 반환 값으로 가진다 } void main() { SimpleCat *Frisky = new SimpleCat; //객체포인터 cout<<(*Frisky).GetAge(); //포인터를 사용한 함수 호출1 Frisky –>SetAge(5); //포인터를 사용한 함수 호출2 cout<<Frisky –>GetAge(); delete Frisky; }

  10. Reference 참조자란 : 특정 객체에 대한 다른 이름입니다. 참조자를 만들 때 다른 객체의 이름으로 –이를 타겟이라 합니다 참조자 선언: 형을 쓰고 참조 연산자(&)를 쓴 뒤 참조자 이름(타겟)을 씁니다. 참조자 특성: 1.참조자의 주소를 물어보면 그 타겟의 주소가 반환된다 2.객체의 이름을 만들 때 참조자를 사용 3.모든 참조자는 초기화 해주어야 합니다. 4.참조자는 다시 할당되지 않는다. 5.참조자는 null 이 될 수 없다 정수형을 초기화한 참조자 int howBig = 200; int & rIntRef = howBig; 클래스를 초기화한 참조자 -객체에 대한 참조자는 객체 그 자체처럼 사용됩니다 -멤버 자료와 메소드는 클래스 멤버 접근 연산자(.)를 사용하여 접근 Cat frisky; Cat &rCatRef = frisky; rCatRef.GetAge( );

  11. Reference Example1 #include<iostream.h> class SmpleCat { public: // 범용접근 제한자 SimpleCat(int age,int weight); ~SimpleCt(){} int GetAge( ){return itsAge;}//inline int GetWeight( ); private: // 전용접근 제한자 int itsAge; int itsWeight; }; Simple::SimpleCat(int age,int weight) { itsAge = age; itsWeight = weight; } int SimpleCat::GetWeight() { return itsWeight; } void main { SimpleCat Frisky(5,8); // 객체변수를 rCat 참조자로 선언 SimpleCat &rCat = Frisky; cout<<“Frisky is:”; cout<<Frisky.GetAge()<<“years old.\n”; cout<<“And Frisky weights: ”; // < 참조자를 사용하여 함수를 호출> cout<<rCat.GetWeight()<<“Pounds.\n”; }

  12. Reference Example2 #include<iostream.h> // <반환 값 없는 원형 함수> void swap(int &x, int &y); void main() { int x=5,y=10; cout<<“main.before swap x:”; cout<<x<<“y:”<<y<<“\n; swap(x,y); // 함수를 호출 //참조자에 의해 x,y 값이 달라진다. cout<<“rX : ”<<x<<“rY :”; cout<<y<<“\n”; } // <인수를 정수형 참조자로 선언했다.> void swap(int &rX, int &rY) { int temp; cout<<“swap. Before swap.rX:”<<rX; cout<<“rY:”<<rY<<“\n”; temp =rX; rX =rY; rY =temp; cout<<swap.After swap,rX:”<<rX; cout<<“rY:”<<rY<<“\n”; }

  13. Inheritance 상속이란: 기존의 클래스에 새로운 기능을 추가한 새로운 클래스를 원래 클래스에서 상속되었다고 합니다. 먼저의 클래스를 베이스 클래스라고 합니다. 상속된 클래스 특성: 상속된 클래스는 동일한 베이스클래스를 공유하게 되어 베이스클래스의 모든 메소드들을 사용할 수 있습니다. 상속구문: 클래스를 선언하면 그 클래스가 어디로부터 상속했는지를 클래스 이름 뒤에 콜론을 쓰고 파생의 형을 쓴 뒤 베이스 클래스명을 쓰면 됩니다. class Dog : public Mammal 접근 제한자: public, private, protected public: 클래스의 public 멤버들은 프로그램 어느 곳에서나 접근이 가능 합니다. private:멤버들은 단지 그 클래스의 객체에만 접근이 가능합니다 protected: 자신의 클래스의 객체와 그 클래스에서 파생된 객체에서만 접근이 가능합니다.

  14. Inheritance Example1 #include<iostream.h> class Vehicle // 상위클래스 { public:// 범용 접근 제한자 void start(){cout<<“시동…\n”;} void move(){cout<<“조종..\n”;} }; // <상속 받은 클래스= 하위클래스> class helicopter:public Vehicle { public: void move(); } void helicpter::move() { cout<<“비행…”<<endl; } void main() { helicopter whily; //객체를 정의 // 상위클래스의 함수를 호출할 수 있다. whily.start(); // 객체의 함수 호출 whily.move(); } // <실행 결과> /* 시동… 비행… */

  15. Inheritance Example2 #include<iostream.h> enum BREED{YORKIE,CAIRN,DANDIE, SHETLAND,DOBERMAN,LAB}; class Mammal // 상위 클래스 { public: // 범용 접근 제한자 Mammal();itsAge(2),itsWeight(5){} ~Mammal(){} int GetAge()const{return itsAge;} void SetAge(int age){ itsAge =age;} int GetWeight()const{return itsWeight;} void SetWeight(int weight){itsWeight = weight;} void Speak() const{cout<<“mammal sound!”;} void Sleep()const{cout<<“I’msleep\n”;} protected: //전용 접근 제한자 int itsAge; int itsWeight; }; class Dog:public Mammal //상속 받은 하위클래스 { public: Dog():itsBreed(YORKIE){} ~Dog(){} BREED GetBreed()const{ return itsBreed;} void SetBreed(BREED breed){ itsBreed = breed;} void WagTail(){cout<<“Tail wagging…\n”;} void BegForFood(){cout<<“Begging for food..\n”;} private: BREED itsBreed; }; int main() { Dog fido; fido.Speak();// 상위클래스의 함수 호출 fido.WagTail(); cout<<“Fido is”<<fido.GetAge()<<“years old\n”; }

  16. Polymorphism 다중상속: 하나 이상의 베이스 클래스에서 파생 클래스 를 만드는 것이 가능 합니다. 이름 다중 상속 이라 합니다. 하나 이상의 클래스로부터 파생 하기 위해 각 베이스 클래스 를 쉼표로 분리합니다. 다중상속 선언법: 하나 이상의 클래스로부터 상속받는 객체를 선언하려면 클래스 이름 뒤에 콜론을 하고 원하는 베이스 클래스의 이름들을 쉼표로 분리하여 적습니다. class Pegasus: public Horse , public Bird class Schnoodle:public Schnauzer,public Poodle 가상 상속의 클래스 선언: 파생 클래스가 단지 공통 베이스 클래스 중 하나만을 사용하고자 할 때 ,중간의 클래스를 원하는 베이스 클래스로부터 가상적으로 상속 받도록 합니다. 이것은 베이스 클래스의 함수에 대한 모호성을 제거 해줍니다. class Horse : virtual public Animal class Bird : virtual public Animal class Pegasus : public Horse,public Bird

  17. Polymorphism Example1 #include<iostream.h> Class Horse{ public:// 범용접근 제한자 Horse(){cout<<“horse constructor..”;} virtual ~Horse(){cout<<“Horse destructor..\n”} virtual void Whinny()const{cout<<“Whinny!.”;} private:// 전용접근 제한자 int itsAge; }; class Bird{ public: Bird(){cout<<“Bird condstuctor..”;} virtual ~Bird(){cout<<“bird destruntor”;} virtual void chirp()const{cout<<“chirp..”;} virtual void Fly()const{Cout<<“I can Fly!”;} private: int itsWeight; }; class Pegasus: public Horse, public Bird { // 다중 상속 public: void Chirp()const{Whinny();} Pegasus(){cout<<“Pegasus constructor..”;} ~Pegasus(){cout<<“Pegasus destructor..”;} }; const int MagicNumber =2; void main() { Horse * Ranch[MagicNumber]; Bird* Aviary[MagicNumber]; Horse * pHorse; Bird* pBird; int choice; for(int i = 0 ;i<MagicNumber ; i++) { cout<<“\n(1)Horse(2)Pegasus:”;

  18. Polymorphism Example1 cin>>choice; if(choice = = 2) pHorse = new Pegasus; else pHorse = new Horse; Ranch[i] = pHorse; } for(i=0 ; i<MagicNumber ; i++) { cout<<“\n(1)Bird(2)Pegasus:”; cin>>choice; if(choice = = 2) pBird = new Pegasus; else pBird = new Bird; Aviary[i] = pBird; } cout<<“\n”; for(i=0 ; i<MagicNumber ; i++) { cout<<“\n Ranch [ “<< i <<“ ]:”; Ranch[I]->Whnny(); delete Ranch[i]; } for(i=0 ; i<MagicNumber ;i++) { cout<<“\n Aviary [“ << i << “ ]: ” ; Aviary[i]->Chirp(); Aviary[i]->fly(); delete Aviary[i]; } }

  19. Static Member Data ,Static Function 정적(static) 멤버 자료: -멤버변수에 클래스객체를 만들지 않고도 이름을 완전하게 주면 접근할 수 있습니다. -public 접근자로 선언되어 있어야 합니다. -객체의 부분이 아니며 메모리를 할당 받지 않습니다. -클래스의 바깥부분에서 정의되고 초기화 되어야 합니다. 정적(static)함수: -멤버변수에 클래스 객체를 만들지않고도 이름을 완전하게 주면 접근할 수 있습니다. -public 접근자로 선언 되어 있어야 합니다. -객체의 부분이 아니며 메모리를 할당 받지 않습니다. -객체 내에서만 존재하는 것이 아니라 클래스 의 범위 내에서 존재합니다. #include<iostream.h> Class Cat{ public://범용 접근제한자 Cat(int age):itsAge(age){HowmanyCat++;} virtual ~Cat( ){HowManyCats--;} virtual int GetAge( ){return itsAge;} virtual void SetAge(int age){itsAge =age;} static int HowManyCats; //정적 멤버 변수 private: Int itsAge; // 전용 멤버 변수 }; int Cat::HowManyCats =0; void main(){ const int MaxCats =5; Cat *CatHouse[MaxCats]; for(int i=0;i<MaxCats;i++) CatHouse[i] =new Cat(i +2); for(I=0;I<MaxCats;I++) { cout<<Cat::HowManyCats; cout<<CatHouse[I]->GetAge(); delete CatHouse[I]; CatHouse[I] =0; } }

  20. Static Member Data ,Static Function Example #include<iostream.h> Class Cat { public:// 범용 접근 제한자 Cat(int age):itsAge(age){HowManyCats++;} virtual ~Cat(){HowManyCat--;} virtual int GetAge(){return itsAge;} virtual void SetAge(int age){ itsAge=age;} // <정적 멤버 함수> static int GetHowMany(){return HowManyCats;} private: // 범용 접근 제한자 int itsAge; static int HowManyCats; // 정적 멤버 변수 }; int Cat::HowManyCats =0; void TelepathicFunciton(); //원형 함수선언 void main() { const *CatHouse[MaxCats]; for(int I=0;I<MaxCats;I++) { CatHouse[I] =new Cat(I+2); TelepathicFunction(); } for(I=0;I<MaxCats;I++) { delete CatHouse[I]; TelepathicFunction(); CatHouse[I] =0; } } void TelepathicFuntion() //정의 함수 { cout<<Cat::GetHowMany(); }

More Related