2011. 3. 9. 19:39

virtual 함수는,
최종적으로 오버라이딩 한 함수를 제외하고 나머지 함수는 가려지게 된다.

static binding : 컴파일하는 동안(컴파일-타임)에 호출될 함수가 결정. (호출될 함수가 이미 고정되어 있는것.)

dynamic binding : 컴파일 하는 동안(컴파일-타임)에 호출될 함수가 결정되는 것이 아니라, 실행하는 동안(런-타임)에 호출될 함수가 결정된다. 포인터가 가리키는 객체가 무엇이냐에 따라서 그 문장이 호출되는 함수는 유동적이다.
다형성의 한 예("모양은 같은데 형태는 다르다.")

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
public:
 virtual void fct()
 {
  cout<<"AAA"<<endl;
 }
};
class BBB : public AAA
{
public:
 void fct()    //virtual 키워드를 삽입하지 않더라도 자동적으로 virtual void fct()화 됨.
 {
  cout<<"BBB"<<endl;
 }
};

class CCC : public BBB
{
public:
 void fct()
 {
  cout<<"CCC"<<endl;
 }

};

int main(void)
{
 BBB b;
 b.fct(); //static binding
 AAA* a = new BBB;
 a->fct(); //dynaminc binding

 delete a;
 return 0;
}




####virtual 함수를 사용하지 않은 예제결과와 비교해 볼것~!

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
public:
 void fct()
 {
  cout<<"AAA"<<endl;
 }
};
class BBB : public AAA
{
public:
 void fct()
 {
  cout<<"BBB"<<endl;
 }
};

class CCC : public BBB
{
public:
 void fct()
 {
  cout<<"CCC"<<endl;
 }

};

int main(void)
{
 BBB b;
 b.fct(); //static binding
 AAA* a = new BBB;
 a->fct(); //dynaminc binding

 delete a;
 return 0;
}





[오버라이딩 된 함수 호출하기]
방법 : 범위 지정 연산자를 이용.
a->AAA::fuct(); 의 방식으로 사용.
Posted by Triany
2011. 3. 8. 13:31

Hungarian notation

From Wikipedia, the free encyclopedia
Jump to: navigation, search

Hungarian notation is an identifier naming convention in computer programming, in which the name of a variable or function indicates its type or intended use. There are two types of Hungarian notation: Systems Hungarian notation and Apps Hungarian notation.

Hungarian notation was designed to be language-independent, and found its first major use with the BCPL programming language. Because BCPL has no data types other than the machine word, nothing in the language itself helps a programmer remember variables' types. Hungarian notation aims to remedy this by providing the programmer with explicit knowledge of each variable's data type.

In Hungarian notation, a variable name starts with a group of lower-case letters which are mnemonics for the type or purpose of that variable, followed by whatever name the programmer has chosen; this last part is sometimes distinguished as the given name. The first character of the given name can be capitalised to separate it from the type indicators (see also CamelCase). Otherwise the case of this character denotes scope.

Contents

[hide]

[edit] History

The original Hungarian notation, which would now be called Apps Hungarian, was invented by Charles Simonyi, a programmer who worked at Xerox PARC circa 1972-1981, and who later became Chief Architect at Microsoft. It may have been derived from the earlier principle of using the first letter of a variable name to set its type — for example, variables whose names started with letters I through N in FORTRAN were integers by default.

The notation is a reference to Simonyi's nation of origin; Hungarian people's names are "reversed" compared to most other European names; the family name precedes the given name. For example, the anglicized name "Charles Simonyi" in Hungarian was originally "Simonyi Charles". In the same way the type name precedes the "given name" in Hungarian notation rather than the more natural, to most Europeans, Smalltalk "type last" naming style e.g. aPoint and lastPoint. This latter naming style was most common at Xerox PARC during Simonyi's tenure there. It may also be inspired by play on the name of an almost entirely unrelated concept, Polish notation.

The name Apps Hungarian was coined since the convention was used in the applications division of Microsoft. Systems Hungarian developed later in the Microsoft Windows development team. Simonyi's paper referred to prefixes used to indicate the "type" of information being stored. His proposal was largely concerned with decorating identifier names based upon the semantic information of what they store (in other words, the variable's purpose), consistent with Apps Hungarian. However, his suggestions were not entirely distinct from what became known as Systems Hungarian, as some of his suggested prefixes contain little or no semantic information (see below for examples).

The term Hungarian notation is memorable for many people because the strings of unpronounceable consonants vaguely resemble the consonant-rich orthography of some Eastern European languages despite the fact that Hungarian is a Finno-Ugric language, and unlike Slavic languages is rather rich in vowels. For example the zero-terminated string prefix "sz" is also a letter in the Hungarian alphabet.

[edit] Systems vs. Apps Hungarian

Where Systems notation and Apps notation differ is in the purpose of the prefixes.

In Systems Hungarian notation, the prefix encodes the actual data type of the variable. For example:

  • lAccountNum : variable is a long integer ("l");
  • arru8NumberList : variable is an array of unsigned 8-bit integers ("arru8");
  • szName : variable is a zero-terminated string ("sz"); this was one of Simonyi's original suggested prefixes.
  • bReadLine(bPort,&arru8NumberList) : function with a byte-value return code.

Apps Hungarian notation strives to encode the logical data type rather than the physical data type; in this way, it gives a hint as to what the variable's purpose is, or what it represents.

  • rwPosition : variable represents a row ("rw");
  • usName : variable represents an unsafe string ("us"), which needs to be "sanitized" before it is used (e.g. see code injection and cross-site scripting for examples of attacks that can be caused by using raw user input)
  • strName : Variable represents a string ("str") containing the name, but does not specify how that string is implemented.

Most, but not all, of the prefixes Simonyi suggested are semantic in nature. The following are examples from the original paper: [1]

  • pX is a pointer to another type X; this contains very little semantic information.
  • d is a prefix meaning difference between two values; for instance, dY might represent a distance along the Y-axis of a graph, while a variable just called y might be an absolute position. This is entirely semantic in nature.
  • sz is a null- or zero-terminated string. In C, this contains some semantic information because it's not clear whether a variable of type char* is a pointer to a single character, an array of characters or a zero-terminated string.
  • w marks a variable that is a word. This contains essentially no semantic information at all, and would probably be considered Systems Hungarian.
  • b marks a byte, which in contrast to w might have semantic information, because in C the only byte-sized data type is the char, so these are sometimes used to hold numeric values. This prefix might clear ambiguity between whether the variable is holding a value that should be treated as a letter (or more generally a character) or a number.

While the notation always uses initial lower-case letters as mnemonics, it does not prescribe the mnemonics themselves. There are several widely used conventions (see examples below), but any set of letters can be used, as long as they are consistent within a given body of code.

It is possible for code using Apps Hungarian notation to sometimes contain Systems Hungarian when describing variables that are defined solely in terms of their type.

[edit] Relation to sigils

In some programming languages, a similar notation now called sigils is built into the language and enforced by the compiler. For example, in BASIC, name$ names a string and count% names an integer, and in Perl, $name refers to a scalar variable while @namelist refers to an array. Sigils have the notable advantages over Hungarian notation that they implicitly define the type of the variable without need for redundant declaration, and are also checked by the compiler, preventing omission and misuse.

On the other hand, such systems are in practice less flexible than Hungarian notation, typically defining only a few different types — the lack of adequate easy-to-remember symbols obstructs more extensive use.

[edit] Examples

  • bBusy : boolean
  • chInitial : char
  • cApples : count of items
  • dwLightYears : double word (systems)
  • fBusy : boolean (flag)
  • nSize : integer (systems) or count (application)
  • iSize : integer (systems) or index (application)
  • fpPrice: floating-point
  • dbPi : double (systems)
  • pFoo : pointer
  • rgStudents : array, or range
  • szLastName : zero-terminated string
  • u32Identifier : unsigned 32-bit integer (systems)
  • stTime : clock time structure
  • fnFunction : function name

The mnemonics for pointers and arrays, which are not actual data types, are usually followed by the type of the data element itself:

  • pszOwner : pointer to zero-terminated string
  • rgfpBalances : array of floating-point values
  • aulColors : array of unsigned long (systems)

While Hungarian notation can be applied to any programming language and environment, it was widely adopted by Microsoft for use with the C language, in particular for Microsoft Windows, and its use remains largely confined to that area. In particular, use of Hungarian notation was widely evangelized by Charles Petzold's "Programming Windows", the original (and for many readers, the definitive) book on Windows API programming. Thus, many commonly-seen constructs of Hungarian notation are specific to Windows:

  • For programmers who learned Windows programming in C, probably the most memorable examples are the wParam (word-size parameter) and lParam (long-integer parameter) for the WindowProc() function.
  • hwndFoo : handle to a window
  • lpszBar : long pointer to a zero-terminated string

The naming convention guidelines for .NET Framework, Microsoft's more recent software development platform, advise that Hungarian notation should not be used.[2]

The notation is sometimes extended in C++ to include the scope of a variable, separated by an underscore. This extension is often also used without the Hungarian type-specification:

  • g_nWheels : member of a global namespace, integer
  • m_nWheels : member of a structure/class, integer
  • m_wheels : member of a structure/class
  • s_wheels : static member of a class
  • _wheels : local variable

[edit] Advantages

(Some of these apply to Systems Hungarian only.)

Supporters argue that the benefits of Hungarian Notation include:[1]

  • The variable type can be seen from its name
  • The type of value returned by a function is determined without lookup (i.e. searching for function definitions in other files, e.g. ".h" header files, etc.)
  • The formatting of variable names may simplify some aspects of code refactoring
  • Multiple variables with similar semantics can be used in a block of code: dwWidth, iWidth, fWidth, dWidth
  • Variable names can be easy to remember from knowing just their types.
  • It leads to more consistent variable names
  • Deciding on a variable name can be a mechanical, and thus quick, process
  • Inappropriate type casting and operations using incompatible types can be detected easily while reading code
  • Useful with string-based languages where numerics are strings (Tcl for example)
  • In Apps Hungarian, the variable name guards against using it in an improper operation with the same data type by making the error obvious as in:
heightWindow = window.getWidth()
  • When programming in a language that uses dynamic typing or that is completely untyped, the decorations that refer to types cease to be redundant. Such languages typically do not include declarations of types (or make them optional), so the only sources of what types are allowed are the names themselves, documentation such as comments, and by reading the code to understand what it does. In these languages, including an indication of the type of a variable may aid the programmer. As mentioned above, Hungarian Notation expanded in such a language (BCPL).
  • In complex programs with lots of global objects (VB/Delphi Forms), having a basic prefix notation can ease the work of finding the component inside of the editor. Typing btn and pressing <Ctrl-Space> causes the editor to pop up a list of Button objects.
  • Applying Hungarian notation in a narrower way, such as applying only for member variables helps avoiding naming collision.

[edit] Disadvantages

Most arguments against Hungarian notation are against System Hungarian notation, not Apps Hungarian notation. Some potential issues are:

  • The Hungarian notation is redundant when type-checking is done by the compiler. Compilers for languages providing type-checking ensure the usage of a variable is consistent with its type automatically; checks by eye are redundant and subject to human error.
  • All modern Integrated development environments display variable types on demand, and automatically flag operations which use incompatible types, making the notation largely obsolete.
  • Hungarian Notation becomes confusing when it is used to represent several properties, as in a_crszkvc30LastNameCol: a constant reference argument, holding the contents of a database column LastName of type varchar(30) which is part of the table's primary key.
  • It may lead to inconsistency when code is modified or ported. If a variable's type is changed, either the decoration on the name of the variable will be inconsistent with the new type, or the variable's name must be changed. A particularly well known example is the standard WPARAM type, and the accompanying wParam formal parameter in many Windows system function declarations. The 'w' stands for 'word', where 'word' is the native word size of the platform's hardware architecture. It was originally a 16 bit type on 16-bit word architectures, but was changed to a 32-bit on 32-bit word architectures, or 64-bit type on 64-bit word architectures in later versions of the operating system while retaining its original name (its true underlying type is UINT_PTR, that is, an unsigned integer large enough to hold a pointer). The semantic impedance, and hence programmer confusion and inconsistency from platform-to-platform, is on the assumption that 'w' stands for 16-bit in those different environments.
  • Most of the time, knowing the use of a variable implies knowing its type. Furthermore, if the usage of a variable is not known, it can't be deduced from its type.
  • Hungarian notation strongly reduces the benefits of using feature-rich code editors that support completion on variable names, for the programmer has to input the whole type specifier first.
  • It may make code less readable, by making variables look more similar to each other.[citation needed]
  • The additional type information can insufficiently replace more descriptive names. E.g. sDatabase doesn't tell the reader what it is. databaseName might be a more descriptive name.
  • When names are sufficiently descriptive, the additional type information can be redundant. E.g. firstName is most likely a string. So naming it sFirstName only adds clutter to the code.

[edit] Notable opinions

  • Linus Torvalds (against systems Hungarian):

    "Encoding the type of a function into the name (so-called Hungarian notation) is brain damaged—the compiler knows the types anyway and can check those, and it only confuses the programmer."[3]

  • Steve McConnell (for Hungarian):

    "Although the Hungarian naming convention is no longer in widespread use, the basic idea of standardizing on terse, precise abbreviations continues to have value. ... Standardized prefixes allow you to check types accurately when you're using abstract data types that your compiler can't necessarily check."[4]

  • Bjarne Stroustrup (against systems Hungarian for C++):

    "No I don't recommend 'Hungarian'. I regard 'Hungarian' (embedding an abbreviated version of a type in a variable name) a technique that can be useful in untyped languages, but is completely unsuitable for a language that supports generic programming and object-oriented programming—both of which emphasize selection of operations based on the type an arguments (known to the language or to the run-time support). In this case, 'building the type of an object into names' simply complicates and minimizes abstraction."[5]

  • Joel Spolsky (for apps Hungarian):

    "If you read Simonyi’s paper closely, what he was getting at was the same kind of naming convention as I used in my example above where we decided that us meant “unsafe string” and s meant “safe string.” They’re both of type string. The compiler won’t help you if you assign one to the other and Intellisense won’t tell you bupkis. But they are semantically different; they need to be interpreted differently and treated differently and some kind of conversion function will need to be called if you assign one to the other or you will have a runtime bug. If you’re lucky. (...) There’s still a tremendous amount of value to Apps Hungarian, in that it increases collocation in code, which makes the code easier to read, write, debug, and maintain, and, most importantly, it makes wrong code look wrong."[6]

  • Microsoft has discouraged the use of Hungarian notation in the .NET design guidelines,[2] which was common on earlier Microsoft development platforms like Visual Basic 6 and earlier.

[edit] References

[edit] External links

'Windows Prog' 카테고리의 다른 글

-  (0) 2011.12.24
[펌] 프린터 관련 함수  (0) 2011.11.10
그동안 건강에 너무도 소홀했다  (0) 2011.11.05
[Ruby] editor 다운로드  (0) 2011.10.29
[Ruby] Ruby의 특징  (0) 2011.10.29
Posted by Triany
2011. 3. 7. 21:42

<명시적인 것만을 허용!! explicit>
=>묵시적인 호출을 허용하지 않는다.
=>객체 생성관계를 분명히 하고자 하는 경우에 주로 사용.

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
public:
 explicit AAA(int n)
 {
  cout<< "explicit AAA(int n)"<< endl;
 }
};

int main(void)
{
 AAA a1=10; //묵시적으로 변환 -> AAA a1(10); //Compile Error!!!
 return 0;
}



<예외를 둔다! : mutable>
=>const로 멤버함수가 상수화 되면 이 함수는 멤버 변수를 변경시키지 못한다.
그러나 멤버변수가 mutable로 선언이 되면 상수화된 멤버 변수라 할지라도 데이터 변경이 가능해 진다!!

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
private:
 mutable int val;
 int val2;
public:
 void SetData(int a, int b) const
 {
  val1=a; //val1이 mutable이므로 가능!!!!
  val2=b; //Error!!!!
 }
};

int main(void)
{
 AAA a1;
 a1.SetData(10, 20);
 return 0;
}

,, mutable은 프로그램에 유연성을 제공한다는 장점이 있지만,,
권장하지 않는다......!!

출처: 열혈강의 c++


Posted by Triany
2011. 3. 7. 21:35
static 멤버의 특징
1) main 함수가 호출되기도 전에 메모리 공간에 올라가서 초기화 된다. 따라서 public으로 선언이 된다면, 객체 생성 이전에도 접근이 가능하다.
2) 객체의 멤버로 존재하는 것이 아니다. 다만 선언되어 있는 클래스 내에서 직접 접근할 수 있는 권한이 부여된 것이다.



int Person::count=1; //static 멤버 초기화

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

 

class Person
{
 char name[20];
 int age;
 static int count;

public:
 Person(char* _name, int _age)
 {
  strcpy(name, _name);
  age=_age;
  
cout<<count++<<"번째 Person 객체 생성"<<endl;
 }
 void ShowData()
 {
  cout<<"이름 : "<<name<<endl;
  cout<<"나이 : "<<age<<endl;
 }
};

int Person::count=1; //static 멤버 초기화

int main(void)
{
 Person p1("LEE",13);
 Person p2("JUNG",22);
 return 0;
}



외부에서 static 멤버 접근법 => static 멤버가 public에 선언되어 있을 경우 가능
Person::count
Posted by Triany
2011. 3. 7. 21:13
const 멤버함수
멤버함수에 const 키워드를 붙여주는것은,
=> "멤버 함수를 상수화 하겠다."는 뜻.
멤버 함수가 상수화 되면, 이 함수를 통해서 멤버 변수의 값이 변경되는 것을 허용하지 않는다.!



int* GetPtr() const{
    return &cnt;
}      //컴파일 요류
상수화된 함수는 상수화되지 않은 함수의 호출을 허용하지 않을 뿐만 아니라,
멤버 변수의 포인터를 리턴하는 것도 허용하지 않는다.

해결책!!!
const int* GetPtr() const{
    return &cnt;
}
=>리턴하고자 하는 포인터를 상수화해서 리턴.  포인터 자체를 상수화하는 것이 아니라, 포인터가 가리키는 데이터를 상수화는것. 따라서 이 포인터를 전달받은 영역에서는 멤버 변수를 참조할 수는 있어도 조작하는 것은 불가능.
컴파일 오류는 NO!


const객체
객체가 상수화되면,
어떠한 경로를 통해서든, 멤버 변수의 조작은 불가능.
상수화된 멤버 함수만 호출 가능.
일반 멤버함수는 멤버 변수를 조작하지 않더라도 호출 불가능!!

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
 int num;
public:
 AAA(int _num) : num(_num) {}
 void Add(int n)
 {
  num+=n;
 }
 void ShowData()
 {
  cout<<num<<endl;
 }
};

int main(void)
{
 const AAA aaa(10);
 aaa.Add(10); //Compile Error
 aaa.ShowData(); //Compile Error

 return 0;
}




ShowData() 함수는 num을 조작하지 않고 단지 보여주는 역할만 한다.
ShowData()함수를 사용하고 싶을 때 => ShowData()를 상수화!

@@@ 상수함수냐 아니냐에 따라서도 함수 오버로딩은 성립! @@@
void function(int n) const {......}
void function(int n) {.....}

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
 int num;
public:
 AAA(int _num) : num(_num) {}
 void Add(int n)
 {
  num+=n;
 }
 void ShowData()
 {
  cout<<num<<endl;
 }
 
void ShowData() const
 {
  cout<<"void ShowData() const 호출!!"<<endl;
  cout<<num<<endl;
 }
};

int main(void)
{
 const AAA aaa(10);
 aaa.ShowData(); //Compile Error

 return 0;
}

Posted by Triany
2011. 3. 7. 21:06
학번같은 변하지 않는 상수 정보를 안정적으로 프로그래밍 하려면
const int id; //학번
의 방식으로 const키워드를 쓰는 것이 좋다.
하지만 다음과 같이 프로그래밍을 할 경우, 컴파일에서 오류가 발생하게 된다.

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class Student
{
 const int id; //학번
 int age;//나이
 char name[20]; //이름
 char major[30]; //학과
public:
 
Student(int _id, int _age, char* _name, char* _major)
 {
  id=_id;
  age=_age;
  strcpy(name,_name);
  strcpy(major,_major);
 }
 void ShowData()
 {
  cout<<"이름: "<<name<<endl;
  cout<<"나이: "<<age<<endl;
  cout<<"학번: "<<age<<endl;
  cout<<"학과: "<<age<<endl;
 }
};
int main()
{
 Student Kim(20051577, 20, "Kim Gil Jung", "Computer Science");
 Student Hong(20091122,20,"Hong mi wyoun", "Architecture");

 Kim.ShowData();
 cout<<endl;
 Hog.ShowData();

}


오류를 살펴보자.
우리가 객체를 생성할 때 객체의 생성순서중 첫번째 단계는 '메모리 할당'이다.
이때 객체의 멤버 변수를 위한 메모리 공간도 할당되면서, id 값은 쓰레기 값으로 할당될 것이다.
따라서 이미 한번 초기화 되었으므로 생성자를 통한 초기화는 허용되지 않는다. 값의 변경으로 인식하기 때문이다.

이때 해결책!!
"멤버 이니셜라이저(member initializer)"이다.!
이것을 사용하면 const 멤버 변수를 초기화 하는 것이 가능하다.

  Student(....) : id(_id)
  => "멤버 변수 id를 매개 변수 _id로 초기화하라"

 둘 이상의 const 멤버도 ,(콤마) 연산자를 이용해서 구분 지어 초기화가 가능하다.

수정예제는 다음과 같다.

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class Student
{
 const int id; //학번
 int age;//나이
 char name[20]; //이름
 char major[30]; //학과
public:
 Student(int _id, int _age, char* _name, char* _major) : id(_id)
 {
  age=_age;
  strcpy(name,_name);
  strcpy(major,_major);
 }
 void ShowData()
 {
  cout<<"이름: "<<name<<endl;
  cout<<"나이: "<<age<<endl;
  cout<<"학번: "<<age<<endl;
  cout<<"학과: "<<age<<endl;
 }
};
int main()
{
 Student Kim(20051577, 20, "Kim Gil Jung", "Computer Science");
 Student Hong(20091122,20,"Hong mi wyoun", "Architecture");

 Kim.ShowData();
 cout<<endl;
 Hong.ShowData();

}



참고: 열혈강의 c++


Posted by Triany
2011. 3. 7. 20:53
<const키워드 기능>
1. const 키워드는 변수의 선언 앞에 붙어서 변수를 상수화한다.
const double PI=3.14;
PI=3.1415; //컴파일 오류


2. const 키워드는 포인터가 가리키는 데이터를 상수화한다.
int n=10;
const int* pN=&n;
*pN=20; //컴파일 오류


3. const 키워드는 포인터 선언 시 이름 앞에 붙어서 포인터 자체를 상수화한다.
int n1=10;
int n2=20;
int* const pN=&n1;
*pN=20; //OK
pN=&n2; //컴파일 오류
=> 현재 pN은 끝까지 n1만을 가리켜야 한다.


참고: 열혈강의 C++

'Language > C언어' 카테고리의 다른 글

memset함수  (0) 2014.05.09
10진수 2진수, 8진수, 16진수로 표현 - - C Programming  (0) 2011.10.06
매크로와 전처리  (0) 2011.03.02
열거형(enum) 자료형  (0) 2011.03.01
문자열 처리함수  (0) 2011.03.01
Posted by Triany
2011. 3. 7. 17:54
<복사생성자가 호출되는 시점>
1. 기존에 생성된 객체로 새로운 객체를 초기화하는 경우
2. 함수 호출 시 객체를 값에 의해 전달하는 경우
3. 함수 내에서 객체를 값에 의해 리턴하는 경우



1. 기존에 생성된 객체로 새로운 객체를 초기화하는 경우

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
public:
 AAA()
 {
  cout<<"AAA() 호출"<<endl;
 }
 AAA(const AAA& a)
 {
  cout<<"AAA(const A& a) 호출"<<endl;
 }
};
int main()
{
 AAA obj1;
 AAA obj2=obj1; //AAA ojb2(obj1)이라는 문장으로 묵시적으로 변환됨

 return 0;
}



2. 함수 호출 시 객체를 값에 의해 전달하는 경우
call-by-value 함수 호출 과정
1) 매개 변수를 위한 메모리 공간 할당
2) 전달 인자 값의 복사
  => 복사생성자의 호출을 통해서 이 과정을 처리

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
public:
 int val;
 AAA()
 {
  cout<<"AAA() 호출"<<endl;
 }
 AAA(int i)
 {
  val=i;
 }
 AAA(const AAA& a)
 {
  cout<<"AAA(const A& a) 호출"<<endl;
  val=a.val;
 }
 void ShowData()
 {
  cout<<"val: "<<val<<endl;
 }
};
void function(AAA a)
{
 a.ShowData();
}
int main()
{
 AAA obj1(30);
 function(obj1);

 return 0;
}




3. 함수 내에서 객체를 값에 의해 리턴하는 경우
- 리턴되는 값은 받아주는 변수가 없더라도, 함수를 호출한 영역으로 복사되어 넘어간다.
- 호출한 영역으로 객체가 복사되어 넘어갈 것.!

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class AAA
{
public:
 int val;
 AAA()
 {
  cout<<"AAA() 호출"<<endl;
 }
 AAA(int i)
 {
  val=i;
 }
 AAA(const AAA& a)
 {
  cout<<"AAA(const A& a) 호출"<<endl;
  val=a.val;
 }
 void ShowData()
 {
  cout<<"val: "<<val<<endl;
 }
};
AAA function(void)
{
 AAA a(10);
 return a;
}
int main()
{
 function(); //function().ShowData();

 return 0;
}





출처: 열혈강의 C++프로그래밍
Posted by Triany
2011. 3. 7. 17:32
아래와 같이 변수를 동적할당 해 줄 경우,
명시적으로 복사생성자를 정의해 주어야 한다.
=>생성자 내에서 동적할당을 하면 반드시 제공해야 하는 것은 소멸자이다. 소멸자가 있어야 메모리 누수(유출)이 발생하지 않는다.
뿐만 아니라 복사 생성자도 정의해야 한다. 그래서 메모리 참조를 막을 수 있다.

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class Person
{
 char *name;
 char *phone;
 int age;
public:
 Person(char* _name, char* _phone, int _age);
 Person(const Person& p);
 ~Person();
 void ShowData();
};
Person::Person(char* _name, char* _phone, int _age)
{
 name = new char[strlen(_name)+1];
 strcpy(name, _name);
 phone = new char[strlen(_phone)+1];
 strcpy(phone, _phone);
 age = _age;
}

Person::Person(const Person& p)

 name = new char[strlen(p.name)+1];
 strcpy(name, p.name);
 phone = new char[strlen(p.phone)+1];
 strcpy(phone, p.phone);
 age = p.age;
}

Person::~Person()
{
 delete[] name;
 delete[] phone;
}
void Person::ShowData()
{
 cout<<"name : "<<name<<endl;
 cout<<"phone: "<<phone<<endl;
 cout<<"age  : "<<age<<endl;
}
int main()
{
 Person p1("KIM", "013-333-5555", 22);
 Person p2=p1; //Person p2(p1);
 return 0;
}


'Language > C++' 카테고리의 다른 글

멤버 이니셜라이저의 필요성 _const 멤버 변수를 초기화  (0) 2011.03.07
복사생성자가 호출되는 시점  (0) 2011.03.07
객체 포인터 배열  (0) 2011.03.04
생성자와 동적할당  (0) 2011.03.04
new / delete  (0) 2011.03.03
Posted by Triany
2011. 3. 4. 23:56

객체 포인터 배열 : 객체를 가리킬 수 있는 포인터로 구성이 되어 있는 배열

예제(new와 delete를 이용해서 어떻게 객체를 동적으로 생성 및 소멸하는지 알게 될것.)

 #include <iostream>
using std::cout;
using std::cin;
using std::endl;

class Point{
 int x;
 int y;
public :
 Point()
 {
  cout<<"Point() call!"<<endl;
  x=y=0;
 }
 Point(int _x, int _y)
 {
  x=_x;
  y=_y;
 }
 int GetX(){ return x;}
 int GetY(){ return y;}
 void SetX(int _x){ x=_x; }
 void SetY(int _y){ y=_y; }
};

int main()
{
 Point* arr[5];

 for(int i=0; i<5; i++)
 {
  arr[i] = new Point(i*2, i*3); //new에 의한 객체 동적 생성
 }
 for(int j=0; j<5; j++)
 {
  cout<<"x:  "<<arr[j]->GetX()<<' ';
  cout<<"y:  "<<arr[j]->GetY()<<endl;;
 }
 for(int k=0; k<5; k++)
 {
  delete arr[k]; //arr[k]가 가리키는 객체 소멸
 }
}


"new Point(i*2, i*3)"의 의미
:i*2와 i*3을 인자로 받을 수 있는 Point 클래스의 생성자를 호출하면서, Point 객체를 생성하라

=> 힙 영역에 생성. 생성된 객체의 주소 값이 Point*(Point 클래스의 포인터)형으로 반환될 것.

C에서 사용한 malloc 함수를 이용해서 객체 생성을 할 수 있을까? 없다!!
malloc 함수는 함수 호출 시 전달되는 인자만큼 단순히 메모리 공간만 할당하는 함수이기 때문이다. 즉 객체의 크기만큼 메모리 공간을 할당할 수는 있을 지라도, 생성자 호출은 이뤄지지 않는다. C++에서 이야기하는 객체의 조건을 만족시키려면, 생성자 호출은 반드시 이뤄져야 한다.
Posted by Triany