SlideShare a Scribd company logo
1 of 21
Download to read offline
9. 객체와 클래스 (고급)
차례
• 생성자와 소멸자
• 포인터 객체와 this 포인터
• 프렌드 함수

2/21
생성자
• 생성자
– 객체가 생성될 때 자동으로 호출되는 멤버 함
수
– 클래스 이름과 같아야 한다.
– 함수 반환값은 없다.
– public 접근 속성을 취해야 한다.
– 변수를 선언하고 초기화하듯이 생성자는 객체
생성 후 멤버변수들의 초기화 등에 사용됨
3/21
소스 9-1 (student1.h)
#ifndef _STUDENT1_H_
#define _STUDENT1_H_
#include <iostream>
using namespace std;
class Student
{
public :
Student(); //생성자
void setScore(const int s1, const int s2, const int s3);
void ShowScore();
void SumAverage();
private :
int score[3], sum;
double average;
};
#else
#endif

4/21
소스 9-2 (student1.cpp) -1
#include "student1.h"
Student::Student() //생성자 정의
{
score[0]=0;
score[1]=0;
score[2]=0;

}

sum=0;
average=0.;

void Student::setScore(const int s1, const int s2, const int s3)
{
score[0]=s1;
score[1]=s2;
score[2]=s3;
}
5/21
소스 9-2 (student1.cpp) -2
void Student::SumAverage()
{
int i;
for (i=0; i<3; i++)
sum=sum+score[i];
}

average=sum/3.;

void Student::ShowScore()
{
int i;

}

for (i=0; i<3; i++)
cout << "점 수 " << i+1 << " : " << score[i] << endl;
cout << "총 점 : " << sum << endl;
cout << "평 균 : " << average << endl;
6/21
소스 9-3 (student1_main.cpp)
#include "student1.h"
int main()
{
Student p1; //객체 생성시 생성자 자동 호출
p1.ShowScore();
cout << "***********************" << endl;
p1.setScore(99,93, 89);
p1.SumAverage();
p1.ShowScore();
}

return 0;

7/21
생성자 오버로딩
• 생성자 오버로딩 : 다른 매개변수를 갖는
여러 개의 생성자 정의가 가능하다. (생성
자도 함수이므로!!!)
class Student
{
public :
Student(); //생성자 – 객체 생성시 매개변수가 없을 때 자동 호출
Student(const int s1, const int s2, const int s3); //생성자 – 객체 생성시 세 개의
정수형 매개변수가 있을 때 자동 호출
void setScore(const int s1, const int s2, const int s3);
void ShowScore();
void SumAverage();
private :
int score[3], sum;
double average;
};
8/21
소스 9-4, 9-5
• student1.h에 생성자 선언 추가
Student(const int s1, const int s2, const int s3);

• student1.cpp에 추가된 생성자 정의
Student::Student(const int s1, const int s2, const int s3)
{
score[0]=s1;
score[1]=s2;
score[2]=s3;
sum=0;
average=0;
}
9/21
소스 9-6
#include "student2.h"
int main()
{
Student p1; //매개변수 없는 생성자 호출
p1.setScore(99,93, 89);
p1.SumAverage();
p1.ShowScore();
cout << "***************************" << endl;
Student p2(80, 56, 100); //매개변수 있는 생성자 호출
p2.SumAverage();
p2.ShowScore();
}

return 0;
10/21
생성자 초기화 목록
• 생성자 함수 정의에서 헤더 부분에 콜론을
입력하고 원하는 멤버의 값을 초기화
Student(const int s1, const int s2, const int s3) //생성자 정의에서
: sum(0), average(0)
{
score[0]=s1;
score[1]=s2;
score[2]=s3;
}

* 생성자 초기화 목록은 클래스 상속에서 상위 클래스의 오버로딩된
생성자를 선별해서 호출할 때 편리하게 사용됨
11/21
복사 생성자
• 객체 생성시 이미 생성된 객체의 멤버 변
수 값을 복사
클래스이름

생성할객체(복사할객체);

• 소스 9-8 (ch09_01.cpp)
– 클래스 CopyObj를 따르는 객체 p1을 생성 한
후 객체 p2를 생성할 때 복사 생성자 사용

12/21
소멸자
• 소멸자
– 객체가 소멸할 때 자동으로 실행되는 함수
– 소멸자 이름은 생성자 이름에 “~” 기호를 앞
부분에 붙인 형태
~Student( ); //소멸자

– 소스 9-9

13/21
포인터 객체
• 포인터 객체
– 동일 클래스의 객체 주소를 저장함
– 포인터 객체의 멤버 참조 연산자 : ->
클래스이름

*포인터객체;

• 포인터 객체 사용 형식
포인터 객체=&객체; //동일한 클래스 객체 주소 저장
포인터 객체->멤버; //포인터 객체를 이용한 멤버 참조
포인터 객체 = new 클래스 이름;
14/21
포인터 객체 예 1
class Student
{
…………………..
};
Student Obj(100, 89, 96); //객체 생성, 생성자 호출
Student *p_Obj;

p_Obj=&Obj; //포인터 객체에 동일 클래스의 객체 주소를 할당
Obj.Sum( );
p_Obj->Sum( );

15/21
포인터 객체 예 2
class Student
{
…………………..
};
Student Obj(100, 89, 96); //객체 생성
Student *p_Obj=new Student(98, 76, 45); //동적 객체 생성
…………………..
delete (p_Obj); //동적 객체 생성으로 확보한 공간 해제

16/21
참조 객체
• 참조 객체
– 객체의 별명
– 선언과 동시에 초기화해야 함!!!
클래스이름

&참조객체이름 = 객체이름;

• 소스 9-10

17/21
this
• this
– 객체 자신을 가리키는 포인터
– 객체가 생성되면 생성된 객체는 this 포인터를
가진다.
– 멤버 함수 내에서 매개변수와 멤버 변수의 이
름이 동일할 경우 객체의 멤버 변수임을 명시
하기 위해 사용

18/21
this 사용 예
class Sample
{
public :
void setScore(const int score); //매개변수가 멤버변수와 동일한 이름
int getScore( );
private:
int score;
};

void Sample::setScore(const int score)
{
Sample::score=score;
}

void Sample::setScore(const int score)
{
this->score=score;
}

19/21
프렌드 함수
• 일반 함수와 달리 특정 클래스와 서로 친
분관계를 허락  private 멤버를 참조할
수 있음!!
• 함수 선언시 친분관계를 설정할 클래스 내
에 class SaleInf
“friend”를 명시함
{
friend int CheckTax2(SaleInf &Obj); //프렌드 함수 선언

public :
private :
};

SaleInf(const double Income);
double getTax();
double Income;
double Tax;
20/21
소스 9-13 (ch09_06.cpp)
#include <iostream>
using namespace std;
class SaleInf
{
friend int CheckTax2(SaleInf &Obj); //
프렌드 함수 선언
public :
private :
};

SaleInf(const double Income);
double getTax();

int CheckTax2(SaleInf &Obj)
{
if (Obj.Income<=0)
return 0;

}
int main()
{

double Income;
double Tax;

SaleInf::SaleInf(const double Income) //생성자
{
this->Income=Income;
}
double SaleInf::getTax() //멤버 함수 정의
{
return Tax;
}

Obj.Tax=Obj.Income*0.03;
return 1;

SaleInf s1(20.4);
CheckTax2(s1);
cout << "세금 : " << s1.getTax() << endl;

}

return 0;

21/21

More Related Content

What's hot

C언어 세미나 - 함수
C언어 세미나 - 함수C언어 세미나 - 함수
C언어 세미나 - 함수SeungHyun Lee
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features SummaryChris Ohk
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기Jongwook Choi
 
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)Sang Don Kim
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부Gwangwhi Mah
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기Chris Ohk
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로Jaeseung Ha
 
C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발흥배 최
 
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Isaac Jeon
 
C++ Advanced 강의 2주차
C++ Advanced 강의 2주차C++ Advanced 강의 2주차
C++ Advanced 강의 2주차HyunJoon Park
 
C++ Advanced 강의 4주차
 C++ Advanced 강의 4주차 C++ Advanced 강의 4주차
C++ Advanced 강의 4주차HyunJoon Park
 
20150212 c++11 features used in crow
20150212 c++11 features used in crow20150212 c++11 features used in crow
20150212 c++11 features used in crowJaeseung Ha
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11흥배 최
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++KWANGIL KIM
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉HyunJoon Park
 

What's hot (20)

C언어 세미나 - 함수
C언어 세미나 - 함수C언어 세미나 - 함수
C언어 세미나 - 함수
 
6 function
6 function6 function
6 function
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary
 
Boost
BoostBoost
Boost
 
프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기프로그래밍 대회: C++11 이야기
프로그래밍 대회: C++11 이야기
 
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부
 
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
[TechDays Korea 2015] 녹슨 C++ 코드에 모던 C++로 기름칠하기
 
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
[NDC2015] C++11 고급 기능 - Crow에 사용된 기법 중심으로
 
C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발
 
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...Nexon Developers Conference 2017 Functional Programming for better code - Mod...
Nexon Developers Conference 2017 Functional Programming for better code - Mod...
 
C++ Advanced 강의 2주차
C++ Advanced 강의 2주차C++ Advanced 강의 2주차
C++ Advanced 강의 2주차
 
C++ Advanced 강의 4주차
 C++ Advanced 강의 4주차 C++ Advanced 강의 4주차
C++ Advanced 강의 4주차
 
WTL 소개
WTL 소개WTL 소개
WTL 소개
 
20150212 c++11 features used in crow
20150212 c++11 features used in crow20150212 c++11 features used in crow
20150212 c++11 features used in crow
 
C++11
C++11C++11
C++11
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11
 
포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++포트폴리오에서 사용한 모던 C++
포트폴리오에서 사용한 모던 C++
 
자바스크립트 클래스의 프로토타입(prototype of class)
자바스크립트 클래스의  프로토타입(prototype of class)자바스크립트 클래스의  프로토타입(prototype of class)
자바스크립트 클래스의 프로토타입(prototype of class)
 
Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉Modern C++의 타입 추론과 람다, 컨셉
Modern C++의 타입 추론과 람다, 컨셉
 

Viewers also liked

12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation웅식 전
 
15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization웅식 전
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main웅식 전
 
절차지향 vs 객체지향
절차지향 vs 객체지향절차지향 vs 객체지향
절차지향 vs 객체지향QooJuice
 
2016년 #implude 안드로이드 단기속성 - 5. 객체
2016년 #implude 안드로이드 단기속성 - 5. 객체2016년 #implude 안드로이드 단기속성 - 5. 객체
2016년 #implude 안드로이드 단기속성 - 5. 객체Sung Woo Park
 
객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)Seung-June Lee
 

Viewers also liked (8)

12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation
 
13. structure
13. structure13. structure
13. structure
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 
절차지향 vs 객체지향
절차지향 vs 객체지향절차지향 vs 객체지향
절차지향 vs 객체지향
 
2016년 #implude 안드로이드 단기속성 - 5. 객체
2016년 #implude 안드로이드 단기속성 - 5. 객체2016년 #implude 안드로이드 단기속성 - 5. 객체
2016년 #implude 안드로이드 단기속성 - 5. 객체
 
객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)객체지향 개념 (쫌 아는체 하기)
객체지향 개념 (쫌 아는체 하기)
 

Similar to 10th

09장 객체와 클래스 (고급)
09장 객체와 클래스 (고급)09장 객체와 클래스 (고급)
09장 객체와 클래스 (고급)유석 남
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oopYoung-Beom Rhee
 
Javascript 교육자료 pdf
Javascript 교육자료 pdfJavascript 교육자료 pdf
Javascript 교육자료 pdfHyosang Hong
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initializationEunjoo Im
 
08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)유석 남
 
Java, android 스터티2
Java, android 스터티2Java, android 스터티2
Java, android 스터티2Heejun Kim
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍Young-Beom Rhee
 
C++ Advanced 강의 1주차
C++ Advanced 강의 1주차C++ Advanced 강의 1주차
C++ Advanced 강의 1주차HyunJoon Park
 
12장 상속 (고급)
12장 상속 (고급)12장 상속 (고급)
12장 상속 (고급)유석 남
 
파이썬 모듈 패키지
파이썬 모듈 패키지파이썬 모듈 패키지
파이썬 모듈 패키지SeongHyun Ahn
 
Design Pattern 3
Design Pattern 3Design Pattern 3
Design Pattern 3Daniel Lim
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)문익 장
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11 웅식 전
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기jongho jeong
 
5장 객체와클래스
5장 객체와클래스5장 객체와클래스
5장 객체와클래스SeoYeong
 
I phone 2 release
I phone 2 releaseI phone 2 release
I phone 2 releaseJaehyeuk Oh
 

Similar to 10th (20)

09장 객체와 클래스 (고급)
09장 객체와 클래스 (고급)09장 객체와 클래스 (고급)
09장 객체와 클래스 (고급)
 
C++에서 Objective-C까지
C++에서 Objective-C까지C++에서 Objective-C까지
C++에서 Objective-C까지
 
프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop프론트엔드스터디 E05 js closure oop
프론트엔드스터디 E05 js closure oop
 
Javascript 교육자료 pdf
Javascript 교육자료 pdfJavascript 교육자료 pdf
Javascript 교육자료 pdf
 
Swift3 subscript inheritance initialization
Swift3 subscript inheritance initializationSwift3 subscript inheritance initialization
Swift3 subscript inheritance initialization
 
08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)08장 객체와 클래스 (기본)
08장 객체와 클래스 (기본)
 
Java, android 스터티2
Java, android 스터티2Java, android 스터티2
Java, android 스터티2
 
06장 함수
06장 함수06장 함수
06장 함수
 
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
스파르탄스터디 E04 Javascript 객체지향, 함수형 프로그래밍
 
C++ Advanced 강의 1주차
C++ Advanced 강의 1주차C++ Advanced 강의 1주차
C++ Advanced 강의 1주차
 
Object C - RIP
Object C - RIPObject C - RIP
Object C - RIP
 
12장 상속 (고급)
12장 상속 (고급)12장 상속 (고급)
12장 상속 (고급)
 
파이썬 모듈 패키지
파이썬 모듈 패키지파이썬 모듈 패키지
파이썬 모듈 패키지
 
Design Pattern 3
Design Pattern 3Design Pattern 3
Design Pattern 3
 
ES6 for Node.js Study 5주차
ES6 for Node.js Study 5주차ES6 for Node.js Study 5주차
ES6 for Node.js Study 5주차
 
Effective c++(chapter 5,6)
Effective c++(chapter 5,6)Effective c++(chapter 5,6)
Effective c++(chapter 5,6)
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11
 
Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기Javascript 조금 더 잘 알기
Javascript 조금 더 잘 알기
 
5장 객체와클래스
5장 객체와클래스5장 객체와클래스
5장 객체와클래스
 
I phone 2 release
I phone 2 releaseI phone 2 release
I phone 2 release
 

More from 웅식 전

12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array웅식 전
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer웅식 전
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function웅식 전
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class웅식 전
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)웅식 전
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료웅식 전
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)웅식 전
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide웅식 전
 
10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스웅식 전
 

More from 웅식 전 (20)

12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function
 
9. pointer
9. pointer9. pointer
9. pointer
 
7. variable scope rule,-storage_class
7. variable scope rule,-storage_class7. variable scope rule,-storage_class
7. variable scope rule,-storage_class
 
6. function
6. function6. function
6. function
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef
 
4. loop
4. loop4. loop
4. loop
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
2 2. operators
2 2. operators2 2. operators
2 2. operators
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide
 
10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스
 

10th

  • 2. 차례 • 생성자와 소멸자 • 포인터 객체와 this 포인터 • 프렌드 함수 2/21
  • 3. 생성자 • 생성자 – 객체가 생성될 때 자동으로 호출되는 멤버 함 수 – 클래스 이름과 같아야 한다. – 함수 반환값은 없다. – public 접근 속성을 취해야 한다. – 변수를 선언하고 초기화하듯이 생성자는 객체 생성 후 멤버변수들의 초기화 등에 사용됨 3/21
  • 4. 소스 9-1 (student1.h) #ifndef _STUDENT1_H_ #define _STUDENT1_H_ #include <iostream> using namespace std; class Student { public : Student(); //생성자 void setScore(const int s1, const int s2, const int s3); void ShowScore(); void SumAverage(); private : int score[3], sum; double average; }; #else #endif 4/21
  • 5. 소스 9-2 (student1.cpp) -1 #include "student1.h" Student::Student() //생성자 정의 { score[0]=0; score[1]=0; score[2]=0; } sum=0; average=0.; void Student::setScore(const int s1, const int s2, const int s3) { score[0]=s1; score[1]=s2; score[2]=s3; } 5/21
  • 6. 소스 9-2 (student1.cpp) -2 void Student::SumAverage() { int i; for (i=0; i<3; i++) sum=sum+score[i]; } average=sum/3.; void Student::ShowScore() { int i; } for (i=0; i<3; i++) cout << "점 수 " << i+1 << " : " << score[i] << endl; cout << "총 점 : " << sum << endl; cout << "평 균 : " << average << endl; 6/21
  • 7. 소스 9-3 (student1_main.cpp) #include "student1.h" int main() { Student p1; //객체 생성시 생성자 자동 호출 p1.ShowScore(); cout << "***********************" << endl; p1.setScore(99,93, 89); p1.SumAverage(); p1.ShowScore(); } return 0; 7/21
  • 8. 생성자 오버로딩 • 생성자 오버로딩 : 다른 매개변수를 갖는 여러 개의 생성자 정의가 가능하다. (생성 자도 함수이므로!!!) class Student { public : Student(); //생성자 – 객체 생성시 매개변수가 없을 때 자동 호출 Student(const int s1, const int s2, const int s3); //생성자 – 객체 생성시 세 개의 정수형 매개변수가 있을 때 자동 호출 void setScore(const int s1, const int s2, const int s3); void ShowScore(); void SumAverage(); private : int score[3], sum; double average; }; 8/21
  • 9. 소스 9-4, 9-5 • student1.h에 생성자 선언 추가 Student(const int s1, const int s2, const int s3); • student1.cpp에 추가된 생성자 정의 Student::Student(const int s1, const int s2, const int s3) { score[0]=s1; score[1]=s2; score[2]=s3; sum=0; average=0; } 9/21
  • 10. 소스 9-6 #include "student2.h" int main() { Student p1; //매개변수 없는 생성자 호출 p1.setScore(99,93, 89); p1.SumAverage(); p1.ShowScore(); cout << "***************************" << endl; Student p2(80, 56, 100); //매개변수 있는 생성자 호출 p2.SumAverage(); p2.ShowScore(); } return 0; 10/21
  • 11. 생성자 초기화 목록 • 생성자 함수 정의에서 헤더 부분에 콜론을 입력하고 원하는 멤버의 값을 초기화 Student(const int s1, const int s2, const int s3) //생성자 정의에서 : sum(0), average(0) { score[0]=s1; score[1]=s2; score[2]=s3; } * 생성자 초기화 목록은 클래스 상속에서 상위 클래스의 오버로딩된 생성자를 선별해서 호출할 때 편리하게 사용됨 11/21
  • 12. 복사 생성자 • 객체 생성시 이미 생성된 객체의 멤버 변 수 값을 복사 클래스이름 생성할객체(복사할객체); • 소스 9-8 (ch09_01.cpp) – 클래스 CopyObj를 따르는 객체 p1을 생성 한 후 객체 p2를 생성할 때 복사 생성자 사용 12/21
  • 13. 소멸자 • 소멸자 – 객체가 소멸할 때 자동으로 실행되는 함수 – 소멸자 이름은 생성자 이름에 “~” 기호를 앞 부분에 붙인 형태 ~Student( ); //소멸자 – 소스 9-9 13/21
  • 14. 포인터 객체 • 포인터 객체 – 동일 클래스의 객체 주소를 저장함 – 포인터 객체의 멤버 참조 연산자 : -> 클래스이름 *포인터객체; • 포인터 객체 사용 형식 포인터 객체=&객체; //동일한 클래스 객체 주소 저장 포인터 객체->멤버; //포인터 객체를 이용한 멤버 참조 포인터 객체 = new 클래스 이름; 14/21
  • 15. 포인터 객체 예 1 class Student { ………………….. }; Student Obj(100, 89, 96); //객체 생성, 생성자 호출 Student *p_Obj; p_Obj=&Obj; //포인터 객체에 동일 클래스의 객체 주소를 할당 Obj.Sum( ); p_Obj->Sum( ); 15/21
  • 16. 포인터 객체 예 2 class Student { ………………….. }; Student Obj(100, 89, 96); //객체 생성 Student *p_Obj=new Student(98, 76, 45); //동적 객체 생성 ………………….. delete (p_Obj); //동적 객체 생성으로 확보한 공간 해제 16/21
  • 17. 참조 객체 • 참조 객체 – 객체의 별명 – 선언과 동시에 초기화해야 함!!! 클래스이름 &참조객체이름 = 객체이름; • 소스 9-10 17/21
  • 18. this • this – 객체 자신을 가리키는 포인터 – 객체가 생성되면 생성된 객체는 this 포인터를 가진다. – 멤버 함수 내에서 매개변수와 멤버 변수의 이 름이 동일할 경우 객체의 멤버 변수임을 명시 하기 위해 사용 18/21
  • 19. this 사용 예 class Sample { public : void setScore(const int score); //매개변수가 멤버변수와 동일한 이름 int getScore( ); private: int score; }; void Sample::setScore(const int score) { Sample::score=score; } void Sample::setScore(const int score) { this->score=score; } 19/21
  • 20. 프렌드 함수 • 일반 함수와 달리 특정 클래스와 서로 친 분관계를 허락  private 멤버를 참조할 수 있음!! • 함수 선언시 친분관계를 설정할 클래스 내 에 class SaleInf “friend”를 명시함 { friend int CheckTax2(SaleInf &Obj); //프렌드 함수 선언 public : private : }; SaleInf(const double Income); double getTax(); double Income; double Tax; 20/21
  • 21. 소스 9-13 (ch09_06.cpp) #include <iostream> using namespace std; class SaleInf { friend int CheckTax2(SaleInf &Obj); // 프렌드 함수 선언 public : private : }; SaleInf(const double Income); double getTax(); int CheckTax2(SaleInf &Obj) { if (Obj.Income<=0) return 0; } int main() { double Income; double Tax; SaleInf::SaleInf(const double Income) //생성자 { this->Income=Income; } double SaleInf::getTax() //멤버 함수 정의 { return Tax; } Obj.Tax=Obj.Income*0.03; return 1; SaleInf s1(20.4); CheckTax2(s1); cout << "세금 : " << s1.getTax() << endl; } return 0; 21/21