Why do I need discrete mathematics?

To think logically and mathematically. To achieve these goals, this text stresses
mathematical reasoning and the different ways problems are solved. Five important themes
are interwoven in this text: mathematical reasoning, combinatorial analysis, discrete structures,
algorithmic thinking, and applications and modeling.

 A successful discrete mathematics course should carefully blend and balance all five themes.

 

There are several important reasons for studying discrete mathematics.

First, through this course you can develop your mathematical maturity:

that is, your ability to understand and create mathematical arguments.You will not get
very far in your studies in the mathematical sciences without these skills.

 

Second, discrete mathematics is the gateway to more advanced courses in all parts of the mathematical sciences.

Discrete mathematics provides the mathematical foundations for
many computer science courses including data structures, algorithms, database theory, automata
theory, formal languages, compiler theory, computer security, and operating systems.

One student has sent me an e-mail message saying that she used the contents of this book in every computer science course she took!

 

 

 

What is discrete mathematics?

Discrete mathematics is the part of mathematics devoted to the study of discrete objects. (Here discrete means consisting of distinct or unconnected elements.)

 

  The kinds of problems solved using discrete mathematics include:

 

  •  How many ways are there to choose a valid password on a computer system?
  •  What is the probability of winning a lottery?
  •  Is there a link between two computers in a network?
  •  How can I identify spam e-mail messages?
  •  How can I encrypt a message so that no unintended recipient can read it?
  •  What is the shortest path between two cities using a transportation system?
  •  How can a list of integers be sorted so that the integers are in increasing order?
  •  How many steps are required to do such a sorting?
  •  How can it be proved that a sorting algorithm correctly sorts a list?
  •  How can a circuit that adds two integers be designed?
  •  How many valid Internet addresses are there?

이번 Discrete Mathematics 과정을 마치면 위의 질문에 대해서 설명할 수 있어야 한다.

You will learn the discrete structures and techniques needed to solve problems such as these.

 

Importance of discrete mathematics
    More generally, discrete mathematics is used whenever objects are counted, when relationships
    between finite (or countable) sets are studied, and when processes involving a finite number of steps are analyzed.

A key reason for the growth in the importance of discrete mathematics is
that information is stored and manipulated by computing machines in a discrete fashion.

 

Difficulties of Studying discrete mathematics

Many students find their introductory discrete mathematics course to be significantly more
challenging than courses they have previously taken. One reason for this is that one of the
primary goals of this course is to teach mathematical reasoning and problem solving, rather
than a discrete set of skills.
The exercises in this book are designed to reflect this goal. Although
there are plenty of exercises in this text similar to those addressed in the examples, a large

percentage of the exercises require original thought. This is intentional. The material discussed
in the text provides the tools needed to solve these exercises, but your job is to successfully
apply these tools using your own creativity.

 

One of the primary goals of this course is to lear how to attack problems that may be somewhat

different from any you may have previously seen. Unfortunately, learning how to solve only particular

types of exercises is not sufficient for success in developing the problem-solving skills needed

in subsequent courses and professional work. This text addresses many different topics, but

discrete mathematics is an extremely diverse and large area of study. One of my goals as an author

is to help you develop the skills needed to master the additional material you will need in your own future pursuits.

 

 


 

교재: Discrete Mathematics and Its Applications 저자: K. H. Rosen 출판사: McGraw Hill

 

Discrete Mathematics And Its Applications (SIE) is a study of mathematical structures that are fundamentally discrete rather than continuous. Discrete objects can often be enumerated by integers, and more formally, deal with countable sets.

This renowned, which has been used at over 600 institutions around the world, gives a focused introduction to the primary themes in a Discrete Mathematics course. It helps demonstrate the relevance and practicality of Discrete Mathematics to a wide variety of real-world applications. These application can be used in the fields of computer science, data networking, psychology, chemistry, engineering, linguistics, biology, business, and others. The 7th edition of Discrete Mathematics And Its Applications (SIE) was published by Tata McGraw-Hill Publishing Company in the year 2011. It is available in paperback.

Key Features:

  • It has a new chapter on algebraic structures in coding theory.
  • There are added topics to this book such as validity problem and incompleteness theorem, exponential generating function, domain transformation, range transformation, platonic solid, cut set, and circle.
Review of this book.

 

 

 

- :설명 불분명  <-Amazon에서의 대부분 평가

+:(I believe they present topics such as set theory, elementary number theory, discrete probability, combinatorics, graph theory etc. as though you won't ever take another course nor read a book on such topics. If that's you, then you may like Rosen or Epp.)

+: I find it very easy and straightforward. However i also supplement with youtube videos like MIT's free ones

 

Book Review: This book covers various topics related to Discrete Mathematics which include algorithmic thinking, combinatorial analysis, mathematical reasoning and discrete structures. The book presents various concepts of discrete mathematics in a practical manner. The book also presents the immediate applications of discrete mathematics in various fields pertaining to engineering and medicine.

 

Other Good Textbook on Discrete Mathematics

 

1.oncrete Mathematics: A Foundation for Computer Science, By Donald Knuth

(Need prerequisite to this book is a background in the basic concepts of discrete math)

(You will only need it if you for doing advanced proofs in DS/Algorithms.)

(Discrete Math knowledge is needed to become adept in proving the correctness and deriving the complexity of algorithms and data structures)

 

2.“Discrete Mathematics” by Norman L Biggs

 

Book Review: This book gives a clear understanding on different topics of discrete mathematics which includes number theory, graph theory, combinatorics and abstract algebra. There are many chapters on new topics of discrete mathematics which are natural numbers, integers and logical frameworks.

 

3. “Discrete Mathematics for Computer Science” by Kenneth Bogart and Robert L Drysdale

 

Book Review: This book is written keeping in mind the computer science students thereby providing them the foundation that they need in discrete mathematics subject. The book covers variety of topics including summation notation, unions of sets, intersection of sets, logarithms and exponentiation notations along with traditional explanations. This books covers topics that are of great use to computer scientists which contains advanced topics of data structures which include hashing, recursion, sorting and searching. The book also contains pseudocodes for algorithms.

 

4. “Discrete Mathematics with Applications” by Thomas Koshy

 

Book Review: This book provides information about various courses like linear algebra, number theory, compiler, data structures and algorithms. It also demonstration of discrete mathematics in the field of computer science. The book also interprets problem solving techniques, pattern recognition and numeric computations.

 

 

Goals of a Discrete Mathematics Course

 

1. Mathematical Reasoning:

Students must understand mathematical reasoning in order to
read, comprehend, and construct mathematical arguments. This text starts with a discussion
of mathematical logic, which serves as the foundation for the subsequent discussions of
methods of proof. Both the science and the art of constructing proofs are addressed. The
technique of mathematical induction is stressed through many different types of examples
of such proofs and a careful explanation of why mathematical induction is a valid proof
technique.

 

2. Combinatorial Analysis:

An important problem-solving skill is the ability to count or enumerate
objects. The discussion of enumeration in this book begins with the basic techniques
of counting. The stress is on performing combinatorial analysis to solve counting problems
and analyze algorithms, not on applying formulae.

 

3. Discrete Structures:

A course in discrete mathematics should teach students how to work
with discrete structures, which are the abstract mathematical structures used to represent
discrete objects and relationships between these objects. These discrete structures include
sets, permutations, relations, graphs, trees, and finite-state machines.

 

4. Algorithmic Thinking:

Certain classes of problems are solved by the specification of an
algorithm. After an algorithm has been described, a computer program can be constructed
implementing it. The mathematical portions of this activity, which include the specification
of the algorithm, the verification that it works properly, and the analysis of the computer
memory and time required to perform it, are all covered in this text. Algorithms are described
using both English and an easily understood form of pseudocode.

 

5. Applications and Modeling:

Discrete mathematics has applications to almost every conceivable
area of study. There are many applications to computer science and data networking
in this text, as well as applications to such diverse areas as chemistry, biology, linguistics,
geography, business, and the Internet. These applications are natural and important uses of
discrete mathematics and are not contrived. Modeling with discrete mathematics is an extremely
important problem-solving skill, which students have the opportunity to develop by
constructing their own models in some of the exercises.

 

Features of the Book

 

ACCESSIBILITY This text has proved to be easily read and understood by beginning
students. There are no mathematical prerequisites beyond college algebra for almost all the
content of the text. Students needing extra help will find tools on the companion website for
bringing their mathematical maturity up to the level of the text. The few places in the book
where calculus is referred to are explicitly noted. Most students should easily understand the
pseudocode used in the text to express algorithms, regardless of whether they have formally
studied programming languages. There is no formal computer science prerequisite.
Each chapter begins at an easily understood and accessible level. Once basic mathematical
concepts have been carefully developed, more difficult material and applications to other areas
of study are presented.

 

 

FLEXIBILITY This text has been carefully designed for flexible use. The dependence
of chapters on previous material has been minimized. Each chapter is divided into sections of
approximately the same length, and each section is divided into subsections that form natural
blocks of material for teaching. Instructors can easily pace their lectures using these blocks.


WRITING STYLE The writing style in this book is direct and pragmatic. Precise mathematical
language is used without excessive formalism and abstraction. Care has been taken to
balance the mix of notation and words in mathematical statements.


MATHEMATICAL RIGORAND PRECISION All definitions and theorems in this text
are stated extremely carefully so that students will appreciate the precision of language and
rigor needed in mathematics. Proofs are motivated and developed slowly; their steps are all
carefully justified. The axioms used in proofs and the basic properties that follow from them
are explicitly described in an appendix, giving students a clear idea of what they can assume in
a proof. Recursive definitions are explained and used extensively.


WORKEDEXAMPLES Over 800 examples are used to illustrate concepts, relate different
topics, and introduce applications. In most examples, a question is first posed, then its solution
is presented with the appropriate amount of detail.


APPLICATIONS The applications included in this text demonstrate the utility of discrete
mathematics in the solution of real-world problems. This text includes applications to a wide variety
of areas, including computer science, data networking, psychology, chemistry, engineering,
linguistics, biology, business, and the Internet.


ALGORITHMS Results in discrete mathematics are often expressed in terms of algorithms;
hence, key algorithms are introduced in each chapter of the book. These algorithms
are expressed in words and in an easily understood form of structured pseudocode, which is
described and specified in Appendix 3. The computational complexity of the algorithms in the
text is also analyzed at an elementary level.


HISTORICAL INFORMATION The background of many topics is succinctly described
in the text. Brief biographies of 83 mathematicians and computer scientists are included as footnotes.
These biographies include information about the lives, careers, and accomplishments of
these important contributors to discrete mathematics and images, when available, are displayed.
In addition, numerous historical footnotes are included that supplement the historical information
in the main body of the text. Efforts have been made to keep the book up-to-date by
reflecting the latest discoveries.


KEY TERMS AND RESULTS A list of key terms and results follows each chapter. The
key terms include only the most important that students should learn, and not every term defined
in the chapter.


EXERCISES There are over 4000 exercises in the text, with many different types of
questions posed. There is an ample supply of straightforward exercises that develop basic skills,
a large number of intermediate exercises, and many challenging exercises. Exercises are stated
clearly and unambiguously, and all are carefully graded for level of difficulty. Exercise sets
contain special discussions that develop new concepts not covered in the text, enabling students
to discover new ideas through their own work.
Exercises that are somewhat more difficult than average are marked with a single star ∗;
those that are much more challenging are marked with two stars ∗∗. Exercises whose solutions
require calculus are explicitly noted. Exercises that develop results used in the text are clearly
identified with the right pointing hand symbol . Answers or outlined solutions to all odd

numbered exercises are provided at the back of the text. The solutions include proofs in which
most of the steps are clearly spelled out.


REVIEW QUESTIONS A set of review questions is provided at the end of each chapter.
These questions are designed to help students focus their study on the most important concepts
and techniques of that chapter. To answer these questions students need to write long answers,
rather than just perform calculations or give short replies.


SUPPLEMENTARY EXERCISE SETS Each chapter is followed by a rich and varied
set of supplementary exercises. These exercises are generally more difficult than those in the
exercise sets following the sections. The supplementary exercises reinforce the concepts of the
chapter and integrate different topics more effectively.


COMPUTER PROJECTS Each chapter is followed by a set of computer projects. The
approximately 150 computer projects tie together what students may have learned in computing
and in discrete mathematics. Computer projects that are more difficult than average, from both
a mathematical and a programming point of view, are marked with a star, and those that are
extremely challenging are marked with two stars.


COMPUTATIONS AND EXPLORATIONS A set of computations and explorations is
included at the conclusion of each chapter. These exercises (approximately 120 in total) are designed
to be completed using existing software tools, such as programs that students or instructors
have written or mathematical computation packages such as MapleTM or MathematicaTM.
Many of these exercises give students the opportunity to uncover new facts and ideas through
computation. (Some of these exercises are discussed in the Exploring Discrete Mathematics
companion workbooks available online.)


WRITING PROJECTS Each chapter is followed by a set of writing projects. To do these
projects students need to consult the mathematical literature. Some of these projects are historical
in nature and may involve looking up original sources. Others are designed to serve as gateways
to new topics and ideas. All are designed to expose students to ideas not covered in depth in
the text. These projects tie mathematical concepts together with the writing process and help
expose students to possible areas for future study. (Suggested references for these projects can
be found online or in the printed Student’s Solutions Guide.)


APPENDIXES There are three appendixes to the text. The first introduces axioms for real
numbers and the positive integers, and illustrates howfacts are proved directly from these axioms.
The second covers exponential and logarithmic functions, reviewing some basic material used
heavily in the course. The third specifies the pseudocode used to describe algorithms in this text.


SUGGESTED READINGS A list of suggested readings for the overall book and for each
chapter is provided after the appendices. These suggested readings include books at or below
the level of this text, more difficult books, expository articles, and articles in which discoveries
in discrete mathematics were originally published. Some of these publications are classics,
published many years ago, while others have been published in the last few years.

 

 

Key to the Exercises
no marking         A routine exercise
∗                      A difficult exercise
∗∗                     An extremely challenging exercise
                       An exercise containing a result used in the book (Table 1 on the
                       following page shows where these exercises are used.)
(Requires calculus ) An exercise whose solution requires the use of limits or concepts
from differential or integral calculus


The best approach is to try exercises yourself before you consult the answer section at the end of this book.

Note that the odd-numbered exercise answers provided in the text are answers
only and not full solutions; in particular, the reasoning required to obtain answers is omitted in these answers. The Student’s Solutions Guide, available separately, provides complete, worked
solutions to all odd-numbered exercises in this text. When you hit an impasse trying to solve an odd-numbered exercise, I suggest you consult the Student’s Solutions Guide and look for some guidance as to how to solve the problem. The more work you do yourself rather than passively
reading or copying solutions, the more you will learn.

The answers and solutions to the evennumbered exercises are intentionally not available from the publisher; ask your instructor if you
have trouble with these.

 

 


 

 

Point In Each Chapter Related To The Five Important Themes

 

C H A P T E R 1. The Foundations: Logic and Proofs

In this chapter, we will explain what makes up a correct mathematical argument and introduce
tools to construct these arguments.We will develop an arsenal of different proof methods
that will enable us to prove many different types of results. After introducing many different
methods of proof, we will introduce several strategies for constructing proofs. We will introduce
the notion of a conjecture and explain the process of developing mathematics by studying
conjectures.

 

The rules of logic specify the meaning of mathematical statements. For instance, these rules
help us understand and reason with statements such as “There exists an integer that is
not the sum of two squares” and “For every positive integer n, the sum of the positive integers
not exceeding n is n(n + 1)/2.” Logic is the basis of all mathematical reasoning, and of all
automated reasoning
. It has practical applications to the design of computing machines, to the
specification of systems, to artificial intelligence, to computer programming, to programming
languages, and to other areas of computer science, as well as to many other fields of study.

 

1.1 Propositional Logic
1.2 Applications of Propositional Logic
1.3 Propositional Equivalences
1.4 Predicates and Quantifiers
1.5 Nested Quantifiers
1.6 Rules of Inference
1.7 Introduction to Proofs
1.8 Proof Methods and Strategy

 To understand mathematics, we must understand what makes up a correct mathematical argument, that is, a proof.

Once we prove a mathematical statement is true, we call it a theorem.

A collection of theorems on a topic organize what we knowabout this topic.To learn a mathematical topic, a person needs to actively construct mathematical arguments on this topic, and not just read exposition.

Moreover, knowing the proof of a theorem often makes it possible to modify
the result to fit new situations.


문자열 함수

 

문자열.method() 처럼 쓰이며, string class type의 멤버함수들로 정의되어 있다고 생각하면 이해하기 쉽다.


※문자열 함수는 내부에서 문자열의 copy본을 받아서 변경된 문자열 값만을 그대로 return 하기 때문에 반환된 값을 따로 변수에 저장하는 과정이 필요하다.

 

1. startswith()

 

output type은 bool type이다.

 

Exercise - 단어의 첫 글자 확인하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 트럼프 대통령 트윗을 공백 기준으로 분리한 리스트입니다. 수정하지 마세요.
trump_tweets = ['thank''you''to''president''moon''of''south',
 'korea''for''the''beautiful''welcoming''ceremony''it''will''always''be''remembered']
 
 
def print_korea(text):
    '''
    문자열로 구성된 리스트에서 k로 시작하는 문자열을 출력합니다.
    '''
    
    # 아래 print_korea() 함수를 완성하세요.
    for word in text:
        if(word.startswith('k')):
            print(word)
    
 
print_korea(trump_tweets)
cs

 

* 1. list 순회에서의 print_korea() method에 같은 기능을 수행한다.

 

 

 

2. split()

문자열을 whitespace를 default delimeter로 인식하여 whitespace단위로 구분한 list를 반환한다.

 

1
2
intro = "My name is devgraphy"
print(intro.split())
cs

 

 

 

 

추가적으로, split() 의 argument로 delimeter(구분자)를 입력시켜 줄 수 있다. delimeter를 입력해주면 그 delimeter단위로 끊어 리스트를 반환하게 된다.

 

만약에 delimeter로 ' '(whitespace 하나)를 입력해주면 어떻게 될까? delimeter 하나 단위로 구분하지만 동일한 연속된 2개이상의 delimeter가 나올 땐 delimeter 하나 뺀 만큼의 수의 빈 문자('')들을 리스트로 갖는다. "왜 이런 중복된 delimeter에 대해 한번에 처리해주지 않고 또 한번 또는 여러 번의 처리의 여지를 남겨놓는 걸까?" 라는 의문을 들게 한다. 수고로움이 더 남은 것이지만 꼼꼼한 데이터 처리를 위해서 더 나은 결과일 수 있다!

 

 

또 다른 대표적인 공백문자을 살펴보자.

'\t' : tab                                '\n' : Enter , 

 

Exercise - 문장을 단어 단위로 구분하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 트럼프 대통령의 트윗으로 구성된 문자열입니다. 수정하지 마세요. 
trump_tweets = "thank you to president moon of south korea for the beautiful welcoming ceremony it will always be remembered"
 
 
def break_into_words(text):
    '''
    공백 기준으로 분리된 문자열을 리스트형으로 반환합니다. 
    
    >>> break_into_words('merry christmas')
    ['merry', 'christmas']
    '''
    
    # 아래 break_into_words() 함수를 수정하세요.
    
    words = text.split()
    
    return words
 
# 함수를 완성한 후 아래 코드의 주석을 해제하고 결과를 확인해보세요.  
print(break_into_words(trump_tweets))
cs

 

 

 

 

 

3. lower(), upper()

python에서 소문자와 대문자 문자열은 서로 다른 문자열로 인식한다. 분석할 때 똑같은 문자열로 간주하기 위해 lower, upper함수를 사용한다.

 

1
2
3
intro = "My name is Elice!"
print(intro.upper())
print(intro.lower())
cs

 

 

 

이번엔 lower() method의 실행 방법을 좀 더 살펴보자. 다음 코드의 결과를 예상해 보자.

 

1
2
3
intro = "My name is Elice!"
intro.lower()
print(intro)
cs

 

lower() method를 실행했을 때, 단지 바꿔서 return해주는 함수이다. 따로 intro variable의 값을 변경시키지는 않는 구현이 아님을 알면 된다.

 

 

1
2
3
intro = "My name is Elice!"
intro = intro.lower()
print(intro)
cs

 

비로소 intro의 값은 바뀌어 저장된다.

 

 

 

Exercise - 대소문자 변환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 트럼프 대통령의 트윗 세개로 구성된 리스트입니다. 수정하지 마세요.
trump_tweets = [
    "FAKE NEWS - A TOTAL POLITICAL WITCH HUNT!",
    "Any negative polls are fake news, just like the CNN, ABC, NBC polls in the election.",
    "The Fake News media is officially out of control.",
]
 
 
def lowercase_all_characters(text):
    '''
    리스트에 저장된 문자열을 모두 소문자로 변환합니다.
    
    >>> lowercase_all_characters(['FAKE NEWS', 'Fake News'])
    ['fake news', 'fake news']
    '''
    
    processed_text = []
    
    # 아래 lowercase_all_characters() 함수를 완성하세요. 
    for word in text:
        processed_text.append((word.lower()))
    
    
    
    return processed_text
 
# 함수를 완성한 후 아래 코드의 주석을 해제하고 결과를 확인해보세요.  
print('\n'.join(lowercase_all_characters(trump_tweets)))
cs

 

 

 

 

 

4.replace()

1
2
intro = "제 이름은 devgraphy입니다."
print(intro.replace('devgraphy','데브그래피'))
cs

 

 

 

replace() method는 단순히 문자열을 바꿔주는 기능도 하지만, 특정 문자열을 없애는 역할을 수행하도록 할 수 있다.

다음은 띄어쓰기가 포함된 문장을 띄어쓰기가 없는 이어있는 문자열로 바꾸는 기능을 구현해보자.

 

1
2
intro = "제 이름은 devgraphy입니다."
print(intro.replace(' ',''))
cs

 

 

이 method 역시 바뀐 문자열을 단지 return해준다. 문자열 variable을 수정해주지 않는다. 코드와 결과를 확인해 보자.

1
2
3
intro = "제 이름은 devgraphy입니다."
intro.replace(' ','')
print(intro)
cs

 

 

 

 

 Exercise. 특수기호 삭제하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 트럼프 대통령의 트윗 세개로 구성된 리스트입니다. 수정하지 마세요.
trump_tweets = [
    "i hope everyone is having a great christmas, then tomorrow it’s back to work in order to make america great again.",
    "7 of 10 americans prefer 'merry christmas' over 'happy holidays'.",
    "merry christmas!!!",
]
 
 
def remove_special_characters(text):
    '''
    리스트에 저장된 문자열에서 쉼표, 작은따옴표, 느낌표를 제거합니다.
    >>> remove_special_characters(["wow!", "wall,", "liberals'"])
    ['wow', 'wall', 'liberals']
    '''
    processed_text = []
    # 아래 remove_special_characters() 함수를 완성하세요.
    for sentence in text:
        sentence = sentence.replace("!", "").replace("'", "").replace(",", "")
        processed_text.append(sentence)
    return processed_text
# 함수를 완성한 후 아래 코드의 주석을 해제하고 결과를 확인해보세요.
print('\n'.join(remove_special_characters(trump_tweets)))
cs

 

 

동시에 여러 문자 또는 문자열의 replace를 수행하고 싶을 땐 line21과 같이 .replace().replace()... 와 같이 써주면 된다.

 

python에서는 큰 따옴표(")와 작은 따옴표(')는 다른 문자이지만 코드에서는 동일한 문자로 간주한다.

C++에서는 문자열의 경우 ""를 이용해 표현해주었지만 python에서는 상관없다. 그리고 argument로 큰 따옴표를 넘길 땐, ('"')와 같이 쓰고 작은 따옴표를 넘길 땐, ("'")와 같이 써준다.

 

 

 

cf. 리스트에 대한 method인 append()를 알아두자.리스트의 마지막 원소 뒤에 argument로 넘겨받은 값을 추가한다.

1
2
3
words = ['hello']
words.append('devgraphy')
print(words)
cs

 

 

 

 


#1. for, in - 문장의 단어를 하나씩 가져오기

 

1
2
3
fruits = ["apple" , "orange""pear"]
for fruit in fruits:
    print(fruit + "는 맛있어")
cs

 

 *CODE DESCRIPTION:

line 1.리스트를 만들 때는 위에서 보는 것과 같이 대괄호([ ])로 감싸 주고 각 요소값들은 쉼표(,)로 구분해 준다.

(리스트명 = [요소1, 요소2, 요소3, ...]) 위는 문자열 리스트이다.

 

line2.

for 변수 in 리스트(또는 튜플, 문자열):
    수행할 문장1
    수행할 문장2
    ...

fruits의 첫 번째 원소인 apple이 fruit에 대입되고 print(fruit + "는 맛있어") 문장을 수행한다. 첫 번째 원소에 대한 함수가 끝났으므로 차례대로 두 번째 원소, 세번째 원소를 각각 fruit에 대입하고 함수 안의 문장을 수행하게 된다.

 

 

 

두 번째로는 range()라는 함수를 이용한 숫자 list라고 생각하면 쉽다. argument로 숫자가 들어가면 그 수보다 하나 작은 값까지 범위를 갖게된다. 코드로 살펴보자.

 

1
2
for i in range(10):
    print(i)
cs

 

 

range(10)은 [0,1,2,...,9] 의 숫자 리스트를 의미하며 위의 for, in의 흐름과 똑같이 각 수가 i에 대입되어 함수의 문장을 수행하게 된다.

 

 

 

 

그렇다면 이번엔 위의 두 개념을 모두 이용하여 문자열 리스트와 수를 매칭하여 출력해보자.

 

1
2
3
fruits = ["apple""orange""pear"]
for i in range(len(fruits)):
    print("과일" + str(i+1+ ": " + fruits[i])
cs

 

 

*CODE DESCRIPTION:

line2. range의 parameter type과 의미에 맞는 len()함수 사용. len() - 리스트의 개수 반환

line3. str로 <int to string> Type conversion, []를 이용한 list indexing. C++의 array indexing과 같음

 

 

 

Exercise

1
2
3
4
5
6
7
8
9
10
11
# 트럼프 대통령의 1월 1~3일 트윗을 각각 리스트의 원소로 저장합니다.
trump_tweets = [
    'Will be leaving Florida for Washington (D.C.) today at 4:00 P.M. Much work to be done, but it will be a great New Year!',
    'Companies are giving big bonuses to their workers because of the Tax Cut Bill. Really great!',
    'MAKE AMERICA GREAT AGAIN!'
]
 
 
# index에 0~2을 차례대로 저장하여 반복문을 실행합니다.
for index in range(len(trump_tweets)):
    print('2018년 1월 ' + str(index+1+ '일: ' + trump_tweets[index])
cs

 

 

 

 

 

 

 

 

#2. indexing - 단어의 일부분 가져오기(slicing)

먼저 리스트 인덱싱에 대해 살펴보자.

 

 

1
2
3
4
5
fruits = ["apple""banana""kiwi""pear"]
last_fruit = fruits[-1]
tropical_fruit = fruits[1:3]
no_apple = fruits[1:]
no_pear = fruits[:3]
cs

 

 

*CODE DESCRIPTION:

line2: C++과 다르게 인덱싱은 range(len(list))에서 -N ~ (N-1) 까지 가능하다. 만약 [-5]나 [4] 등을 인덱싱하면 list index out of range 에러를 내뱉는다.

 

lin3~5: 리스트 슬라이싱이 가능하다. [1:3] 은 1번째 원소부터 2번째 원소까지 리스트를 의미하며, [1:]은 첫 번째부터 마지막 원소, [:3]은 첫 번째 원소부터 2번째 원소까지 포함하는 리스트를 의미한다.

 

 

다음은 문자열 인덱싱을 살펴보자.

 

1
2
3
4
5
word = "superman"
print(word[3])      # 'e'
print(word[-1])     # 'n'
print(word[5:])     # "man"
print(word[:5])     # "super"
cs

 

 

 

Exercise

1
2
3
4
5
6
7
8
9
10
11
12
13
def print_korea(text):
    '''
    문자열로 구성된 리스트에서 k로 시작하는 문자열을 출력합니다.
    '''
 
    # 아래 print_korea() 함수를 완성하세요.
    for word in text:
        if(word[0== 'k'):
            print(word)
 
 
# 함수를 완성한 후 아래 코드의 주석을 해제하고 결과를 확인해보세요.
print_korea(trump_tweets)
cs

 

 

*CODE DESCRIPTION:

line1. argument로 문자열 리스트를 받는 함수를 정의한다.

 

line7. 각 원소를 word에 대입시켜 안의 문장을 수행하게 된다. 위에서 문자열 인덱싱에서도 살펴 보았듯이 각 word의 첫번째 문자를 참조하는 방법은 word[0] 이고 문자'k'와 논리 연산(==)을 수행하여 true이면 안의 if 문 안의 문장을 수행하게 된다.

 

line13. 정의한 함수를 실행한다.

 

 

 

 

위의 line7~9를 다음과 같이 바꿀 수도 있다.

1
2
3
    for i in range(len(text)):
        if(text[i][0== 'k'):
            print(text[i])
cs

 

line2 에서 C++의 array of array(multidimentional array) 개념으로 생각하면 이해하기 쉽다.

사전지식:

1. dynamic allocation

- Allocating Memory with new - http://devgraphy.tistory.com/7?category=810547

- Freeing Memory with delete - http://devgraphy.tistory.com/8?category=810547

Class 코드는 Section 164(http://devgraphy.tistory.com/11?category=810224)와 다른게 없다. 다만, main에서 object를 동적 할당하기 때문에 object 선언하는 부분만 다르다.

int main()
{
    Car* c1 = new Car;    //dynamically create a class object
    cout << *c1;        //print out the object that c1 is pointing
    c1->speedUp();
    cout << *c1;
    c1->speedUp(25);
    cout << *c1;
    Car* c2 = new Car;
    Car* c3 = new Car;
    c1->speedDown(25);
    c2->speedUp(30);
    c3->speedUp(35);
    cout << *c1;
    cout << *c2;
    cout << *c3;
    delete c1;        //memory deallocation
    delete c2;
    delete c3;
}

작성한 class는 object를 생성할 때((line3,9,10)) class 영역에 컴파일되어 올라간다. 이 영역에 올라간 클래스는 설계도(흔한 예로, 붕어빵 틀)로 사용된다. c1은 object가 생성되면서 STACK영역에 올라간다(object의 주소를 STACK에 보관). 생성된 object를 "Instance"라고도 부른다.

c1은 object를 생성할 때 Car(double _v=0) 생성자를 호출한다. 또한 c1은 HEAP에 생성된 object를 reference(참조)한다.

Section 164에서의 object는 STACK 영역에서 빠르게 생성되고 자동으로 STACK에서 소멸된다( block( '}' )을 만남과 동시에!).

STACK에 생성된 c1,c2,c3 Pointer variable들은 HEAP에 생성된 object를 간접적으로 참조한다. 따라서 ->를 이용한다( '.' 과 구분!)

HEAP에는 STACK 영역보다 더 넓고, 필요한 만큼의 memory를 필요할 때 사용하므로 memory leak이 더 적다.

정리하면, object를 HEAP에 생성하는 것을 "object를 동적으로(dynamically) 생성한다"라고 말하며, 사용한 다음에는 반드시 delete를 사용해 제거해야한다. delete를 사용하면, ~Car() destructor를 호출하여 memory에서 object를 제거한다(Memory Deallocation). (Pointer variable c1, c2, c3를 제거하는 게 아니고 따라서 재활용 가능하다)

생성한 object를 delete하지 않으면 HEAP에 memory를 차지하게 된다. 이를 "Memory leak"이라 한다.

[그림: 객체 생성과 용어]

[그림: 객체 생성과 메모리]

 

first knowledge:

 

1. class 구조와 개념

2. friend keyword

3. operator overloading

4. pass by value, pass by reference

 

 

여기서 설명할 은닉화의 개념은 앞에 Exercise에서도 충분히 본 개념들이다. 바로 class의 private: 부분에 들어가는 member field 을 채우는 것을 information hiding, 작은의미로 Encapsulation(은닉화)라고 한다.

 

클래스부터 차근차근 설명해보겠다. 클래스는 중요 data인 member field를 모아서 그룹으로 묶는 역할을 한다. 구조체도 grouping 역할을 한다. member field를 모아 외부에 노출되지 않도록 정보를 하는데, 이를 "information hiding"라고 한다.

 

member field를 private으로, member function을 public으로 선언하면 member field는 숨기고 member function만을 이용하여 member field를 변경할 수 있다. 이것을 information hiding라 하고 작은 의미의 Encapsulation으로 이해하자. 

encapsulation and data hiding

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Car {
private:
    double v;
public:
    Car(int _v = 0) :v(_v) {}    //default constructor
    ~Car()                    //destructor
    {
        cout << "Car disappear!" << endl;
    }
    //member functions
    void speedUp(double _v = 10)
    {
        v += _v;
    }
    void speedDown(double _v = 10)
    {
        v -= _v;
    }
    friend ostream& operator<<(ostream& ostr, const Car& c);    //operator << overloading
};
 
ostream& operator<<(ostream& ostr, const Car& c)
{
    if (c.v == 0)
        ostr << "이 자동차는 현재 정지해 있습니다." << endl;
    else
        ostr << "이 자동차는 현재 " << c.v << " km/h로 달리고 있습니다." << endl;
    return ostr;
}
cs

 

 

*CODE DESCRIPTION:

line3: private member field 선언

line17: normal 함수를 friend로 선언하여 member field에 접근 가능하게 함 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
int main()
{
    Car car1;
    cout << car1;    // operator << overloading
    car1.speedUp();    //automatically assign 10
    car1.speedUp(25);
    cout << car1;
    car1.speedDown(25);
    cout << car1;
    car1.speedDown(10);
    cout << car1;
}
cs

 

 *CODE DESCRIPTION:

line3. class object을 static으로 선언

line4. class object 를 cout object가 받을 수 있도록 operator << overloading을 했기 때문에 가능한 문장이다.

line5. default constructor를 정의했기 때문에 아무 argument가 없어도 자동으로 0으로 셋팅

 

 

 

 

 

/*****************************************************************************************

Full Source Code:

 

 

조언과 틀린 부분에 대해선 언제든지 지적부탁드리며, 보충설명이 필요한 부분에 대해 댓글을

남기시면 업데이트하거나 댓글 달아드리겠습니다.

 

매 포스팅과 source code는 추가적으로 업데이트 될 수 있습니다.

*****************************************************************************************/

 

 

 

목표: 행렬 각 원소를 입력 받고 행렬 출력 및 역행렬을 이용한 연립방정식의 해 등을 구하는 함수를 구현해보자.

사전지식:

1. inline keyword http://devgraphy.tistory.com/10

구조체와 클래스를 이용한 행렬 클래스 만들기 프로젝트는 총 6번에 걸쳐서 발전시킬 것이다. 차차 발전시킬 부분이 처음엔 다소 미흡해 보일 수 있으나 포인팅하여 모호함을 최대한 줄이려고 노력하겠다. 최종본을 원하면 (...url...)

앞서 146과 다른 점은 overloaded operator함수를 inline으로 바꾸는 것 이다. 그 이외는 바뀐 게 없다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Matrix
{
private:
    strMat* _matrix;    //structure to dynamcially assign
 
public:
    Matrix(int row,int col)    //class constructor
    {
        _matrix = new strMat(row, col, 0);
    }
    ~Matrix()                    //class destructor
    {
        cout << "Matrix end!" << endl;
        delete _matrix;
    }
    int getRow()const { return _matrix->row; }
    int getCol()const { return _matrix->col; }
    double getVal(int row, int col)const
    {
        return _matrix->mat[row][col];
    }
};
//inline function
inline ostream& operator<<(ostream& ostrm, const Matrix& m)
{
    for (int i = 0; i < m.getRow(); i++)
    {
        for (int j = 0; j < m.getCol(); j++)
        {
            ostrm << m.getVal(i, j) << "\t";
        }
        ostrm << endl;
    }
    return ostrm;
}
 
cs

※ 앞서 friend Keyword가 inline으로 바뀌었는데, friend와 inline은 적절한 비교대상이 아니다. inline 함수는 Normal 함수와 비교되어야 한다.

단지 코드의 성능 개선의 관점에서 바라보면 된다. 그 이외엔 Normal 함수와 다른게 없다.

행렬 각 원소를 입력 받고 행렬 출력 및 역행렬을 이용한 연립방정식의 해 등을 구하는 함수를 구현해보자.

사전지식:

1. pointer 개념

2. structure 구조와 개념

3. class 구조와 개념

4. friend keyword

5. overator overloading

6. pass by value, pass by reference

 

구조체와 클래스를 이용한 행렬 클래스 만들기 프로젝트는 총 6번에 걸쳐서 발전시킬 것이다. 차차 발전시킬 부분이 처음엔 다소 미흡해 보일 수 있으나 포인팅하여 모호함을 최대한 줄이려고 노력하겠다. 최종본을 원하면 (...url...)

 

앞서 "145. 구조체와 클래스의 비교"에서 우리는 structure와 class가 비슷하지만 다른 점을 살펴 보았다. 그러면 실제로 행렬을 구현하면서 structure와 class의 application에 대해 좀 더 자세히 다뤄보자.

 

structure는 data grouping을 한다고 했고, class는 data grouping에 더불어 member function과 OOP를 구현할 수 있다고 했다.그러면 행렬의 연산은 class를 통해 구현할 수 있고, data grouping은 structure를 통해 구현하여 역할을 명확하게 나눠 표현해볼까한다.

 
struct strMat {
    double **mat;    //pointer to pointer Type to dynamically assign
    int row;
    int col;
    strMat(int _row, int _col, double** _mat)    //constructor
    {
        row = _row;
        col = _col;

        mat = new double*[row];        //dynamic assign
        int rowlen = _col * sizeof(double);    //for memset
        for (int i = 0; row; i++)
        {
            mat[i] = new double[col];    //assign an array in each row element: array of array
            memset(mat[i], 0, rowlen);    //initialize one-dimensioanl array using memset 
            if (_mat) memcpy(mat[i], _mat[i], rowlen);    //copy if get '_mat' argument
        }
    }
    ~strMat()    //delete against memory leak
    {
        for (int i = 0; i < row; i++)
        {
            delete[] mat[i];
        }
        delete[] mat;
    }

};

부담감 없이 보길 바란다. 간단하게 위의 structure 또한 member field, constructor와 destructor로 구성되어 있다. 정말로 structure는 data grouping의 목적으로 쓰였음을 알 수 있다.

*CODE DESCRIPTION:

line3,4,5:

member field에 해당하는 부분이고, 행렬의 데이터 구성요소들이라고 생각하면 된다.

2차원배열(array of array)을 동적으로 할당하기 위해 pointer to pointer type(type**)으로 정의함

line6~19:

constructor 부분. 행렬의 필수 데이터인 row와 column data 그리고 array of array를 받을 수 있는 double pointer(pointer to pointer의 다른 표현)로 객체를 받음.

line7,8:

입력받은 _row, _col로 structure의 member field를 채운다.

우리는 **로 pointer level이 2임을 알 수 있고, mat에 row의 크기를 갖는 double* 타입의 배열을 동적 할당한다.

 (※ double(*)[row]와 구분)

우리는 row 크기를 갖는 array를 갖고 있다. 우리는 array를 index를 통해 접근할 수 있음을 이미 알고 있다.

line12:

memset과 memcpy의 3번 째 argument로 넣어줄 variable을 정의 세 번째 인자는 number of characters로 총 bytes 수를 의미

line13~18:

아까 선언한 row크기를 갖는 array의 각 element에 또 array를 for문을 통한 index로 접근해서 또 array를 정의해주고 초기화     및 대입을 한다. mat[i]로 접근하면서 pointer 마지막 레벨이므로 col의 크기를 갖는 double타입의 array를 정의해준다.

memset으로 초기화하고 만약에 mat object가 들어오면 해당 mat에 있던 데이터들을 그대로 copy한다. (Note. 이때 memset과 memcpy는 1차원 배열 단위로 각각 initialize 하고 copy하는 C-style 함수.)

line20~27. destructor부문. main에서 동적할당이 이루어지고 해제가 모두 이루어졌다면, class에 내에서 동적할당된 메모리는 destructor에서 해제를 정의해주면 된다.

이제 행렬(matrix)에 관한 data definition는 모두 이루어졌다. 이제 class로 무엇을 해야할 지 짐작이 가는가? 행렬에 값만 넣으면 모든 게 끝인가? 당연히 아니다. 우리는 행렬들을 가지고 곱하기 연산, row의 길이와 column의 길이를 얻어오는 연산 등 얼마든지 다양한 기능들을 구현 할 수 있다.  여기서는 row의 길이와 column의 길이를 얻어오고 행렬 특정 element의 값을 출력하는 3개의 기능을 구현해보자. 더불어 <<를 overloading하여 class 객체를 출력해보자( 객체 사이의 기본 연산은 불가능하지만 operator overloading을 이용하면 가능함을 이미 앞서 배웠음).

 
class Matrixs {
private:
    strMat* _matrix;    //declare a structure as a member field
public:
    Matrixs(int row, int col)    //constructor
    {
        _matrix = new strMat(row, col, 0);
    }
    ~Matrixs()                    //destructor
    {
        cout << "Matrix end~" << endl;
        delete _matrix;
    }
    //member function
    int getRow()const { return _matrix->row; }
    int getCol()const { return _matrix->col; }
    double getVal(int row, int col)const
    {
        return _matrix->mat[row][col];
    }
    //operator overloading
    friend ostream& operator << (ostream& ostrm, const Matrixs& m);
};


ostream& operator << (ostream& ostrm, const Matrixs& m)    //operator overloading
{
    for (int i = 0; i < m._matrix->row; i++)
    {
        for (int j = 0; j < m._matrix->col; j++)
        {
            ostrm << m._matrix->mat[i][j] << "\t";    //array of array structure can be assigned with indices
        }
        ostrm << endl;
    }
    return ostrm;
}

 *CODE DESCRIPTION:

line3:

우리는 structure를 통해 data grouping을 모두 끝냈다. 그렇다면 더이상의 data grouping은 할 필요없기때문에 class가

그 structure를 그대로 갖길 원한다. 따라서 strMat type의 object를 member field로 선언해주면 되는데, 여기서 이 strMat

을 동적으로 생성하기 위해 *가 필요하다.

line6~9: class constructor 부분.

parameter로 row, col 값을 요구. 구조체 strMat을 argument로 받은 값을 가지고 strMat 타입의 object를 동적으로(heap memory영역에) 할당. strMat의 constructor에 정의된 대로 class의 constructor를 통해 받은 row, col 값을 그대로 대입. 그리고 세번째 argument로 0은 strMat의 세번째 parmamet인 double** _mat으로 들어가게 되며, pointer 이든 pointer to pointer든 주소값을 가지며, 주소값이 0을 의미한다. 아무런 Matrix객체가 들어오지 않음을 의미한다. strMat의 constructor 부분 맨 마지막 부분의 if(_mat)분기에 접근하지 못한다. 아무런 객체가 들어오지 않았을때 strMat에서는 바로위에 memset으로 먼저 항상 초기화하여 문자가 발생하지 않도록 하였다. (<<if분기로 빠지는 부분은 우리가 앞으로 발전시켜야할 부분이다.)

line9~13: class destructor 부분.

line22,26~37: <<operator overloading.              (링크 필요)

<< 으로 Matrix class object도 출력하게 하기 위함.  

int main()
{

    Matrixs *mat = new Matrixs(10,5 );    //create Matrixs object dynamically assigned
    cout << *mat << endl;
    cout << "--------------------------------" << endl;
    Matrixs mat2(10,5);                    //create Matrixs object statically assigned
    cout << mat2 << endl;
    delete mat;
}
 

 *CODE DESCRIPTION:

line4: Matrixs object를 동적할당

line5: 우리는 << operator overloading 을 통해 class 객체를 출력할 수 있도록 하였고 pointer 변수가 가리키는 object를 출력

line7: 이번엔 class 객체를 정적 할당

line8: line5와 같은 이유로 출력 가능하고, 출력

line9: line4에서 동적할당한 객체를 memory leak를 방지하기 위해 memory 할당 해제(memory deallocate)

Q. main에서 두 개의 object를 생성했다. 하나는 동적할당 또 하난 정적할당이다. 어떤 object가 먼저 memory deallocate를 할까?

 

 

Concept1. Pointers to Pointers

일반적으로, type modifier(* or &)가 declarator에 적용되는 횟수에는 제한이 없다.

(declarator: The part of a declaration that includes the name being defined and an optional type modifier)

 

하나 이상의 modifier가 있을 때, 그것들은 논리적인 방식으로 합쳐지지만 항상 분명하진 않다.

하나의 예로, a pointer를 생각해보자. a pointer는 memory 안에 있는 하나의 object이다. 그래서 여느 object처럼 a pointer 또한 주소를 가지고 있다. 그러므로 우리는 다른 pointer to pointer의 주소를 저장할 수 있수 있게 된다.

 

*로 각 pointer level을 가리키게 된다. 즉, 우리는 pointer to a pointer를 **로 쓰고, pointer to a pointer to a pointer를 *** 써서 제한없이 쓸 수 있다. 

(array of array에 대한 pointer 구조 그림 추가)

 structure(구조체)와 class는 무엇이 다를까? 먼저 정의하는 구조는 비슷하다.

structure는 member field, constructor(생성자), destructor(소멸자) 이 세 가지로 구성된다.

class는 위의 구조체 성분에 member fuction과 OOP(Object-Oriented Programming) 개념이 추가적으로 들어있다.

즉, class는 structure의 구성을 포함하는 개념이다.

(각 구성성분에 대한 설명은 ...참고)

 

structure의 member field가 외부에 쉽게 노출되어 사용하기 편하고 속도도 빠르나, 데이터 보호에는 취약하다.

structure는 중요 데이터를 묶는 data grouping 역할을 한다.

클래스는 data grouping 외에도 중요 데이터를 보호(information hiding)하고, OOP을 할 수 있게 한다.

 

 

 

예를 들어서 설명해보자. 학생에 대한 정보를 담는 구조체를 정의해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct Student {
    char name[50];
    int age;
 
    Student(char* _name, int _age) //constructor -초기화
    {
        strcpy_s(name, _name);
        age = _age;
    }
    ~Student()                    //destructor
    {
        cout << "Die!" << endl;
    }
};
cs

 

 

 

 *CODE DESCRIPTION:

1. 이름이 Student인 structure 생성

2. char형 배열 크기 50을 갖는 이름이 name인 변수 선언 (50byte)

3. 나이 data를 저장하는 이름이 age인 변수 선언(4byte)              member field - data grouping에 해당하는 부분       

5. constructor는 structure의 member field를 초기화 해주는 기능을 한다.

7. strcpy_s는 c-style 문자열(char [] 타입)에 복사해주는 함수이다.

이 함수의 내부는 우리가 배열을 copy할 때 for문을 직접 작성하는 수고로움을 덜어준다.

6. destructor

14. structure 생성 시 {} 뒤에 반드시 ;(semi-colon)을 붙여줘야 한다.

 

 

위에서 우리는 class는 structure를 포함하는 개념이라고 했다.

그러면 class로 이것을 표현하고 부가적으로 어떤 기능들을 추가할 수 있는지 코드를 통해 살펴보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Student {
private:
    char name[50];
    int age;
public:
    Student(char* _name, int _age); //constructor -초기화
    ~Student();                    //destructor
 
    void change(char* _name, int _age);    //특정 structure object의 member field 변경하는 함수
    void change(Student &s);    //객체 주소를 받아(주소에 의한 전달) 값 변경
    void change(Student s);    //객체 copy본을 받아(값에 의한 전달) 값 변경
};
Student::Student(char* _name, int _age) //constructor -초기화
{
    strcpy_s(name, _name);
    age = _age;
}
Student::~Student()                        //destructor
{
    cout << "Die!" << endl;
}
void Student::change(char* _name, int _age)    //특정 structure object의 member field 변경하는 함수
{
    strcpy_s(name, _name);
    age = _age;
}
void Student::change(Student &s)    //객체 주소를 받아(주소에 의한 전달) 값 변경
{
    strcpy_s(s.name,name);
    age = s.age;
}
void Student::change(Student s)        //객체 copy본을 받아(값에 의한 전달) 값 변경
{
    strcpy_s(s.name,name);
    age = s.age;
}
cs

 

 

 

 

 

어떤 것이 달라졌는가?

첫번째, member field를 private으로 선언하여 class 내부에서만 보이도록한다.

이것을 information hiding(정보보호) 또는 encapsulation(은닉화)라고 한다.

은닉화된 class는 외부에서 안의 데이터를 알 수 없다.

 

두번째, member function을 정의할 수 있다.

(여기서는 declaration과 definition을 나누었는데, 클래스는 이렇게 따로 분리할 땐 CLASS_NAME:: 을 추가해야됨을 잊지 말자.)

그래서 우리는 class와 관련된 기능을 수행할 수 있다. 예를 들어 Banking이라는 class에는 withdrawal이라는 기능(member function)을 구현할 수 있게 된다. 이렇게 되면 그냥 main에서 함수를 정의해서 사용하는 것보다 구조와 기능들이 명료해짐을 느낄 수 있다.

 

 *CODE DESCRIPTION:

27. 우리는 객체를 받아와서 class와 관련된 기능을 수행할 수 있다. 외부로 부터 객체(&를 이용)를 argument로 입력해주면

외부로부터 넘겨받은 객체의 data를 변경하는 함수이다. 이것은 단지 "주소에 의한 전달"개념을 짚고 넘어가기 위한 함수이므로

내부 기능은 큰 의미가 없다.

 

32. overloaded function(parameter의 type 또는 parameter의 수로 구분)이다. line27과 기능은 같다. 단지 주소로 받지 않고

객체의 copy본을 받았기 때문에 값을 변경한다해도 s자체는 함수를 시작하면서 생성된 object이고 이것은 이 함수가 끝나면서 소멸된다. 이 함수는 단지 "값에 의한 전달"개념을 짚고 넘어가기 위한 것이므로 프로젝트의 목적과 기능에 따라 line27 함수와 구분하여 사용하면 된다.

 

그렇다면 structure는 그 structure와 관련된 함수를 전혀 수행을 못 하는 것인가?

다음 코드를 살펴보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct Student {
    char name[50];
    int age;
 
    Student(char* _name, int _age) //constructor -초기화
    {
        strcpy_s(name, _name);
        age = _age;
    }
    ~Student()                    //destructor
    {
        cout << "Die!" << endl;
    }
};
Student change(char* _name, int _age)    //특정 structure object의 member field 변경하는 함수
{
    Student s(_name, _age);
    return s;
}
void change(Student &s, char* _name, int _age)    //객체 주소를 받아(주소에 의한 전달) 값 변경
{
    strcpy_s(s.name, _name);
    s.age = _age;
}
void change(Student s,char* _name, int _age)        //객체 copy본을 받아(값에 의한 전달) 값 변경
{
    strcpy_s(s.name, _name);
    s.age = _age;
}
 
cs

 

 

 

멤버함수들이 아닌 일반함수로 그 기능을 대체할 수 있다. 그러므로 CLASS_NAME::도 빠지게 되었다.

 

일반함수로 바뀌었기 때문에 class와 달리 객체와 연관된 member field와 member function의 연산을 바로 수행 할 수 없다.

(ex. Student S1을 선언하고 S1.change를 이용해 S1의 data와의 직접 연산을 할 수 없는 점)

 

따라서 line20, 25처럼 object를 받고 따로 데이터도 받아서 값을 바꿔주거나 line20 처럼 함수 내에서 object를 생성한 후

ojbect를 return하여 다른 object에 assign(할당)하는 방법 등을 생각해 볼 수 있다.

(Note. structure type도 fundamental type처럼 structure object에 assign이 가능하다는 점)

 

 

 

/*****************************************************************************************

Full Source Code: https://github.com/devgraphy/Cpp-200/tree/master/145

 

 

조언과 틀린 부분에 대해선 언제든지 지적부탁드리며, 보충설명이 필요한 부분에 대해 댓글을

남기시면 업데이트하거나 댓글 달아드리겠습니다.

 

매 포스팅과 source code는 추가적으로 업데이트 될 수 있습니다.

*****************************************************************************************/

+ Recent posts