2013. 4. 29. 16:37

* 실제로 포인터를 사용하는 경우들

  - 동적으로 할당된 메모리를 사용하는 경우 ( p = new listNode())

  - 함수의 매개 변수로 변수의 주소를 전달하는 경우

  - 클래스의 멤버변수나 멤버함수를 호출하는 경우

 

1. 동적 메모리와 정적메모리의 차이는?

< 정적 메모리 할당 >

  - 프로그램이 시작되기 전에 미리 정해진 크기의 메모리를 할당 받는 것

      -> 메모리의 크기가 프로그램이 시작하기 전에 결정

      -> 프로그램의 수행 도중에 그 크기는 변경될 수 없다.

 

int i, j;

int buf[80];

char name[] = "hello world";

장점 : 간단하게 메모리 할당

단점 :  입력의 크기를 미리알 수 없는 경우 -> 더 큰 입력이 들어온다면 처리 못함

                                                          -> 더 작은 입력이 들어온다면 남은 메모리 공간 낭비

 

< 동적 메모리 할당(dynamic memory allocation) >

- 실행 도중에 동적으로 메모리를 할당받는 것

- 필요한 만큼의 메모리를 시스템으로 할당(new)  받아서 사용이 끝나면 시스템에 메모리 반납(delete)

 

 

2. 동적 메모리 위치

 - 힙(heap)

 - 힙이란 ? : 코드공간/ 전역공간/ 스택을 제외하고 남은 메모리 영역

 - 힙 장점? : 히프 할당받으면 함수가 종료되더라도 메모리 공간이 없어지지 않음!

                  but!!! 히프에서 할당받은 공간은 반드시 반납하여야 한다. :)

                  => 반납하지 않고 계속 할당만 받으면 시스템이 정지할 수 있음!

* C++에서 메모리의 구분

# 코드공간(code space) : 코드 공간에는 프로그램 코드가 저장된다.

# 전역공간(global namespace) : 전역 공간에는 전역 변수들이 생성된다.

#스택(stack)

  - 스택은 프로그램이 실행하면서 사용하는 공간

  - 주로 함수 호출 시 함수 매개 변수 / 함수의 지역변수를 생성하는 공간

  - 함수호출 후 자동적 소멸

#힙(heap)

 

3. 동적 메모리 반납이 필요한 이유

  동적 할당된 메모리는 자동적으로 반납되지 않는다!

따라서 할당된 메모리를 가리키는 포인터를 항상 가지고 있다가 메모리가 더 이상 필요 없으면 delete를 사용하여 시스템에 반납하여야 한다!!

if, 동적 할당된 메모리를 반납하지 않고 포인터를 없애버리면 메모리를 반납할 방법이 없다.

-> 따라서 메모리를 프로그램이 종료되기 전까지 할당된 상태로 남아있다!

이상태를 ? 메모리 누수(memory leak)!

  ==> 반복적으로 메모리 누수가 일어나면 최종적으로 메모리 부족 현상초래!

 

 

 

 

출처 : POWER C++ / 천인국 저

 

 

 

Posted by Triany
2011. 4. 3. 23:43

<cin> : 문자와 문자열 모두 입력 받을 수 있다.
- 엔터가 나오면 입력종료로 간주.(공백도 마찬가지)

#include <iostream>
void main()
{
 char a, b;
 char str[10];

 cin>>a;  //1
 cout<<a<<endl;  //2


 cin>>a;   //3
 cin>>b;   //4
 cout<<a<<" "<<b<<endl; //5


 cin>>str; //6
 cout<<str<<endl;; //7
 
}

1번에서 p를 입력하고 엔터
2번 출력 결과 => p

3,4번에서,
x입력후 엔터, y입력후 엔터
5번 출력 결과 => x y


6번에서 loving you 엔터
7번에서 출력 결과 =>loving



<get> : get()은 문자만 입력받을 수 있다.

- 이 함수는 개행문자를 입력 큐에 그대로 남겨둔다.

 #include <iostream.h>
void main()
{
 char a, b, c;
 a = cin.get(); //cin.get(a) 가능
 b = cin.get();
 c = cin.get(); //1
 cout<<a<<" "<<b<<" "<< c<<endl; //2
}

1번까지
x입력후 엔터, y입력후 엔터
[2번 출력 결과]
x
y
-즉 엔터도 입력받을 문자로 간주한것으로 볼 수 있습니다.(공백또한 문자로 간주)
x + Enter(개행) + y

cf)cin은 엔터가 나오면 입력 종료로 간주.


cf)getline와 get함수가 다른 점은 get함수는 개행문자를 읽어서 버리지 않고 입력큐에 그대로 남겨둔다는 점이다.

즉, cin.get(str1, hi);
    cin.get(str2, hello);
라는 두 문장이 있다면 입력큐에 개행문자가 그대로 있어서 두번째 호출은 개행문자를 첫 문자로 만나게 된다.
굳이 get()을 써야 한다면,
 cin.get(str1, hi);
 cin.get();
 cin.get(str2, hello);
이렇게 두 문장사이에 get()을 하나 더 삽입하면 된다.

파일에서 읽어들여 올때.. 간단한 사용법

 read ( ifstream  *input_file )
{
 char c;
 while (1)
 {
  input_file->get(c);
  if ( input_file->eof() )
   break;
  else
   cout<<c;
 }
}
 //or
read ( ifstream *input_file )
{
 char c;

 input_file->get(c);
 while (!input_file->eof())
 {
  cout<<c;
  input_file->get(c);
 }
}

 //or ... 이게 제일 편한 방법인듯.
read ( ifstream *input_file )
{
 char c;

 while ( input_file->get(c) )
  cout<<c;
}


 

<getline> : getline()은 문자열만 입력 받는다.
getline(변수의 주소, 최대입력가능 문자수, 종결문자);
-getline()gkatnsms Enter키가 전달하는 개행문자를 입력의 끝으로 인식하여 한줄 전체를 읽는다.
-종결문자 생략시 엔터로 간주된다. 그리고 종결문자를 NULL문자로 바꾼다. 따라서 종결문자전까지 출력하게 된다.
최대입력가능 문자수보다 많은 문자를 입력한 경우 n-1개만큼만 받아들이고 n번째 문자는 null문자로 취급한다.
-cin.getline(a,20); //이때 입력한 문자의 개수는 19개이하이여야 한다.(마지막 1문자는 null문자 삽입)

 #include<iostream>
void main()

{
 char a[10];
 cin.getline(a,10); //1
 cout<<a<<endl;  //2

 cin.getline(a, 10, 'u'); //3
 cout<<a<<endl;  //4

}

1번에서 so cute! 입력후 엔터
2번 결과 => so cute!
cf)cin의 경우 공백이 나오면 입력이 끝났다고 간주, but getline은 공백(ascii 32)도 문자로 받아들임

3번에서 so cute! 입력후 엔터
4번 결과 => so c


 

파일에서 읽어올 경우.. infile->getline(이 위치로, 문자수, 종결문자) 형식.
read(ifstream  *infile) 
{

 SMS S;
 while(!infile->eof())
 { 
  infile->getline(S.phone,21,'\n');
  infile->getline(S.msg, 97,'\n');
  S.time = currentTime();
  insert(S);
 }
}

Posted by Triany
2011. 3. 25. 17:54
출처 : http://www.devarticles.com/c/a/cplusplu ··· right%2F
출처:http://webdizen.new21.net/blog/3110

Are you looking for a way to speed up the debugging process in C++? This article explains how to use asserts to do just that, showing that not all macros are evil.

If a man begins with certainties, he shall end in doubts;

But if he will be content to begin with doubts,

He shall end in certainties.

[Francis Bacon 1561-1626]

Assertive Programming

If there is one thing I have learned over the past few years, it is not to underestimate the power of assert(). It comes with your compiler and can be found either in cassert or assert.h.

The reason I love assert is because it looks after me and helps me find bugs I was sure weren’t there. I mean, we all write bugfree software, right? Yeah right. Well there have been many Kodak moments when an assert fired on something I was dead sure could never happen; I should be a rich man as the look on my face was priceless.

If you are not familiar with asserts, you should start using them right now. Use  assert to check that your code is working the way you expect it to or be prepared to pay the price. No not for my face, but for long nights behind the debugger, ticking away possible problem sources until you have your own Kodak moment.

When do you use assert, you ask? Simple… whenever you can use it to verify the truth of a situation: ‘this pointer can never be null’, ‘this number is never smaller than zero’, ‘there is always at least one customer stored in this list’, ‘this code won’t be used the next millennium, two digits are fine’.

Use proper error handling when you can check for things that can go wrong. Use asserts on things you are sure can’t go wrong.

Trust me… the sillier the assert… the more valuable it is. I tested this once myself, grinning, thinking ‘this is ridiculous, want to bet it will never fire?’, only to have it triggered a couple of months later! And because the assert was so preposterous and silly I immediately knew which conditions were breaking my code.

assert.

  1. To state or express positively, affirm: asserted his innocence
  2. To defend or maintain (one’s rights, for example)

The important thing to remember is that asserts are only compiled into your code when the NDEBUG macro is not defined. So in the final optimized version of your application, they are not there to bloat or to slow things down! The only investment you have to make is typing them out while you are working on those classes and functions. It will pay you back greatly when it helps you shorten the time it takes to track down bugs.

Face it… we all write code on assumptions we make about the situation the code will be running in. Assert you are in that situation, because your code base will grow beyond the picture you have of it in your mind.

Though we will be implementing our customized version of assert here, all you need to do is include assert.h and you are ready to use the assert macro that comes with it:

// assert.h
#ifndef NDEBUG
void __assert(const char *, const char *, int);
#define assert(e) \
     ((e) ? (void)0 : __assert(#e,__FILE__,__LINE__))
#else
#define assert(unused) ((void)0)
#endif

The __assert helper function prints an error message to stderr and the program is halted by calling abort(). It is possible that the implementation that comes with your compiler varies slightly, but you get the idea.

Lets use a simple example function:

void writeString(char const *string) {
assert( 0 != string );
...
}

In the unfortunate situation that the pointer to string is NULL, execution will halt and you will be offered the possibility of opening the debugger and jumping to the location in the source where the assertion failed. This can be very handy as you can examine the call stack, memory, registers, and so forth, and are likely to catch the perpetrator red handed!

Although I am ranting about why you should use assert, this article is aimed at showing you how to implement your own version using preprocessor macros.

Here is a very basic version that doesn’t even halt execution:

#ifndef NDEBUG
# define ASSERT( isOK ) \
( (isOK) ? \
     (void)0 : \
     (void)printf(“ERROR!! Assert ‘%s’ failed on line %d ” \
      “in file ‘%s’\n”, #isOK, __LINE__, __FILE__) )
#else
# define ASSERT( unused ) do {} while( false )
#endif

Notice that we don’t need a helper function to get information onto the screen. (I am sticking to printf in the following examples, but there is nothing stopping you from using fprintf and stderr instead.) The stringize macro operator (#) names the condition for us in the printf statement, adding quotes as well and the predefined __LINE__ and __FILE__ macros help to identify the location of the assert.

The do { } while ( false ) statement for the unused version of assert, I used to make sure that the user cannot forget to conclude his assert statement with a semicolon. The compiler will optimize it away, and I consider it a slightly better way to say that I am not doing anything.

We are only one step away from halting our application’s execution (don’t forget to include stdlib.h):

#ifndef NDEBUG
# define ASSERT( isOK ) \
if ( !isOK ) { \
 (void)printf(“ERROR!! Assert ‘%s’ failed on line %d “ \
  “in file ‘%s’\n”, #isOK, __LINE__, __FILE__) ); \
 abort(); \
}
#else
# define ASSERT( unused ) do {} while ( false )
#endif

In case writeString is called with a NULL pointer now, we are told what went wrong, where it went wrong and the application is halted.

When you are using the Microsoft Visual C++ 7.1 compiler, you’ll be presented with a dialog screen:


After pressing Retry you are presented with more dialogs and finally... you end up in the debugger.

The problem with abort() is that it doesn’t let you resume execution after you’ve concluded that the assert was benign; or maybe you are interested in what happens immediately after the assert? You need to disable the assert (never a good thing), recompile and restart your application.

There are other ways to halt execution and you will have to look in your compiler’s documentation to discover what the correct call is, but with Visual C++ it’s an interrupt call:

__asm { int 3 }

When our application halts again on the writeString function, we’ll encounter the following dialog (did you recognize it? We actually came across this dialog when halting the application with the abort() function!) :

It is not a problem to continue execution now, if we think this is responsible… that is you are often recommended to implement your own assert functionality.

Wouldn’t it be nice to be able to add some hints or remarks along with the location of the assert? When the assert fires and you don’t have a debugger available, this message might still tell you what the problem is:

void writeString(char const *string) {
assert(0!=string, “A null pointer was passed to writeString()!”);
...
}

The simplest solution is to just expand the assert macro and make it accept a message as well as a condition:

#ifndef NDEBUG
# define ASSERT( isOK, message ) \
if ( !(isOK) ) { \
 (void)printf(“ERROR!! Assert ‘%s’ failed on line %d “ \
  “in file ‘%s’\n%s\n”, \
     #isOK, __LINE__, __FILE__, #message); \
  __asm { int 3 } \
 }
#else
# define ASSERT( unused, message ) do {} while ( false )
#endif

Again the stringize operator helps us to stuff the message we want into the printf statement. We could call it a day now, but I am a very lazy coder… I do not want to be forced to put messages into the assert, sometimes I just want to assert.

Of course it is possible to write an ASSERT(condition) and an ASSERTm(condition, message) macro, but did I mention I am a forgetful coder too? I’d much rather have a single ASSERT statement that can do both.

The first thing that comes to mind is the fact I could do this easily with a function:

void MyAssert(bool isOK, char const *message=””) {
if ( !isOK ) {
 (void)printf(“ERROR!! Assert ‘%s’ failed on line %d “
  “in file ‘%s’\n%s\n”,
  __LINE__, __FILE__, message);
 __asm { int 3 } \
}
}

So maybe if I declared another function:

void NoAssert(bool isOK, char const *message=””) {}

And then defined assert as:

#ifndef NDEBUG
# define ASSERT MyAssert
#else
# define ASSERT NoAssert
#endif

While this seems like a quick solution, I have completely lost my extra debug information! The line information is the same now for every assert… oh… the compiler substitutes __LINE__ with the actual line number it is compiling at that moment, and since we are making a function call – all line numbers lead to the MyAssert function!

Alexandrescu demonstrates a great way around this problem [Alexandrescu]. (It is also a great article showing how you can take assertions to a higher level after this one, by making them throw exceptions!)

#ifndef NDEBUG
#define ASSERT \
struct MyAssert { \
MyAssert(bool isOK, char const *message=””) { \
 if ( !isOK ) { \
  (void)printf(“ERROR!! Assert failed in “ \
   “file ‘%s’\n%s\n”, __FILE__, message); \
   __asm { int 3 } \
  } \
 } \
} myAsserter = MyAssert
#endif

For some reason my Visual C++ 7.1 compiler will not accept the __LINE__ macro next to the __FILE__ macro in the code above. The strange thing is that the __FILE__ macro works fine, but with __LINE__ it complains:

error C2065: '__LINE__Var' : undeclared identifier

It is never easy, but I do not want to give up at this point. Since the macro is expanded as a single line into the place where we are calling it, and since the compiler apparently has no objection to me assigning __LINE__ as a default parameter in a constructor, let's try again:

#ifndef NDEBUG
#define ASSERT \
struct MyAssert { \
int mLine; \
MyAssert(int line=__LINE__) : mLine(line) {} \
MyAssert(bool isOK, char const *message=””) { \
 if ( !isOK ) { \
  (void)printf(“ERROR!! Assert failed on “ \
   “line %d in file ‘%s’\n%s\n”, \
   MyAssert().mLine, __FILE__, message); \
  __asm { int 3 } \
 } \
}\
} myAsserter = MyAssert
#endif

Now that we have our line information back, we are nearly there; as soon as we add a second assert, the compiler complains that we are redefining the struct MyAssert! If only we could keep the struct declaration local… and again Alexandrescu shows us how [Alexandrescu]:

#ifndef NDEBUG
#define ASSERT \
if ( false ) {} else struct LocalAssert { \
 int mLine; \
LocalAssert(int line=__LINE__) : mLine(line) {} \
LocalAssert(bool isOK, char const *message=””) { \
 if ( !isOK ) { \
  (void)printf(“ERROR!! Assert failed on “ \
   “line %d in file ‘%s’\n%s\n”, \
   LocalAssert().mLine, __FILE__, message); \
  __asm { int 3 } \
} \
} myAsserter = LocalAssert
#else
#define ASSERT \
if ( true ) {} else struct NoAssert { \
NoAssert(bool isOK, char const *message=””) {} \
} myAsserter = NoAssert
#endif

There is a lot of fun to be had with macros and sometimes it is possible to create the wildest incantations with them [Niebler/Alexandrescu]. I hope you are convinced that despite the fact that they can be considered evil, there is something magical about them as well.

As a final example I will show you how to create personal and customizable debug streams in the next article… all with macros.


References

[STL] – The Standard Template Library

< comes standard with your compiler but this one is very portable>

http://www.stlport.org

[BOOST] – Boost C++ Libraries

http://www.boost.org

[ACE] – The ADAPTIVE Communication Environment

http://www.cs.wustl/edu/~schmidt/ACE.html

[Niebler] – Eric Niebler

“Conditional Love: FOREACH Redux”

http://www.artima.com/cppsource/foreach.html

[Alexandrescu] – Andrei Alexandrescu

Assertions

http://www.cuj.com/documents/s=8248/cujcexp2104alexandr/

 

Posted by Triany
2011. 3. 14. 20:24

출처:http://www.cplusplus.com/reference/iostream/istream/

Output Stream

ostream

ostream objects are stream objects used to write and format output as sequences of characters. Specific members are provided to perform these output operations, which can be divided in two main groups:
  • Formatted output
    These member functions interpret and format the data to be written as sequences of characters. These type of operation is performed using member and global functions that overload the insertion operator (operator<<).
  • Unformatted output
    Most of the other member functions of the ostream class are used to perform unformatted output operations, i.e. output operations that write the data as it is, with no formatting adaptations. These member functions can write a determined number of characters to the output character sequence (put, write) and manipulate the put pointer (seekp, tellp).
Additionaly, a member function exists to synchronize the stream with the associated external destination of characters: sync.

The standard objects cout, cerr and clog are instantiations of this class.

The class inherits all the internal fields from its parent classes ios_base and ios:

Formatting information
  • format flags: a set of internal indicators describing how certain input/output operations shall be interpreted or generated. The state of these indicators can be obtained or modified by calling the members flags, setf and unsetf, or by using manipulators.
  • field width: describes the width of the next element to be output. This value can be obtained/modified by calling the member function width or parameterized manipulator setw.
  • display precision: describes the decimal precision to be used to output floating-point values. This value can be obtained/modified by calling member precision or parameterized manipulator setprecision.
  • fill character: character used to pad a field up to the field width. It can be obtained or modified by calling member function fill or parameterized manipulator setfill.
  • locale object: describes the localization properties to be considered when formatting i/o operations. The locale object used can be obtained calling member getloc and modified using member imbue.
State information
  • error state: internal indicator reflecting the integrity and current error state of the stream. The current object may be obtained by calling rdstate and can be modified by calling clear and setstate. Individual values may be obtained by calling good, eof, fail and bad.
  • exception mask: internal exception status indicator. Its value can be retrieved/modified by calling member exceptions.
Other
  • event function stack: stack of pointers to callback functions that are called when certain events occur. Additional callback functions may be registered to be called when an event occurs, using member function register_callback.
  • internal extensible arrays: two internal arrays to store long objects and void pointers. These arrays can be extended by calling member function xalloc, and references to these objects can be retrieved with iword or pword.
  • pointer to tied stream: pointer to the stream object which is tied to this stream object. It can be obtained/modified by calling member function tie.
  • pointer to stream buffer: pointer to the associated streambuf object. It can be obtained/modified by calling member function rdbuf.

Public members


Formatted output:

Unformatted output:

Positioning:

Synchronization:

Prefix/Suffix:

Member functions inherited from ios


Member functions inherited from ios_base




istream

class
<istream>

Input stream

istream


istream objects are stream objects used to read and interpret input from sequences of characters. Specific members are provided to perform these input operations, which can be divided in two main groups:
  • Formatted input
    These functions extract data from a sequence of characters that may be interpreted and formatted to a value of a certain type. These type of operation is performed using member and global functions that overload the extraction operator ().
  • Unformatted input
    Most of the other member functions of the istream class are used to perform unformatted input, i.e. no interpretation is made on the characters got form the input. These member functions can get a determined number of characters from the input character sequence (get, getline, peek, read, readsome), manipulate the get pointer i(ignore, seekg, tellg, unget) or get information of the last unformatted input operation (gcount).
Additionaly, a member function exists to synchronize the stream with the associated external source of characters: sync.

The standard object cin is an instantiation of this class.

The class inherits all the internal fields from its parent classes ios_base and ios:

Formatting information
  • format flags: a set of internal indicators describing how certain input/output operations shall be interpreted or generated. The state of these indicators can be obtained or modified by calling the members flags, setf and unsetf, or by using manipulators.
  • field width: describes the width of the next element to be output. This value can be obtained/modified by calling the member function width or parameterized manipulator setw.
  • display precision: describes the decimal precision to be used to output floating-point values. This value can be obtained/modified by calling member precision or parameterized manipulator setprecision.
  • fill character: character used to pad a field up to the field width. It can be obtained or modified by calling member function fill or parameterized manipulator setfill.
  • locale object: describes the localization properties to be considered when formatting i/o operations. The locale object used can be obtained calling member getloc and modified using member imbue.
State information
  • error state: internal indicator reflecting the integrity and current error state of the stream. The current object may be obtained by calling rdstate and can be modified by calling clear and setstate. Individual values may be obtained by calling good, eof, fail and bad.
  • exception mask: internal exception status indicator. Its value can be retrieved/modified by calling member exceptions.
Other
  • event function stack: stack of pointers to callback functions that are called when certain events occur. Additional callback functions may be registered to be called when an event occurs, using member function register_callback.
  • internal extensible arrays: two internal arrays to store long objects and void pointers. These arrays can be extended by calling member function xalloc, and references to these objects can be retrieved with iword or pword.
  • pointer to tied stream: pointer to the stream object which is tied to this stream object. It can be obtained/modified by calling member function tie.
  • pointer to stream buffer: pointer to the associated streambuf object. It can be obtained/modified by calling member function rdbuf.

Public members


Formatted input:

Unformatted input:

Positioning:

Synchronization:

Prefix/Suffix:

Member functions inherited from ios


Member functions inherited from ios_base

Posted by Triany
2011. 3. 14. 20:23
p + 3

==

p.operator+(3)

 
class Point {
private:
 int x, y;
public:
 Point(int _x=0, int _y=0):x(_x), y(_y){}
 void ShowPosition();
 void operator+(int val); //operator+라는 이름의 함수
};
void Point::ShowPosition()
{
 cout<<x<<"  "<<y<<endl;
}
void Point::operator+(int val)
{
 x+=val;
 y+=val;
}//operator+라는 이름의 함수

int main(void)
{
 Point p(3,4);
 p.ShowPosition();
 //p.operator +(10);
 p+10;
 p.ShowPosition();
 return 0;
}


<연산자를 오버로딩하는 방법>
1. 멤버 함수에 의한 오버로딩
2. 전역 함수에 의한 오버로딩


1. 멤버함수에 의한 오버로딩

 
class Point {
private:
 int x, y;
public:
 Point(int _x=0, int _y=0):x(_x), y(_y){}
 void ShowPosition();
 void operator+(int val); //operator+라는 이름의 함수
 Point operator+(const Point & p);
};
void Point::ShowPosition()
{
 cout<<x<<"  "<<y<<endl;
}
void Point::operator+(int val)
{
 x+=val;
 y+=val;
}//operator+라는 이름의 함수

Point Point::operator+(const Point & p)
{
 Point temp(x+p.x, y+p.y);
 return temp;
}

int main(void)
{
 Point p1(1, 2);
 Point p2(2, 1);
 Point p3=p1+p2;
 p3.ShowPosition();
 return 0;
}




2. 전역 함수에 의한 오버로딩
클래스에 있는 private로 선언된 변수를 직접 접근하기 위해선,
클래스 내에 friend 선언을 해 두어야 한다.

<오버로딩이 불가능한 연산자>
.              .*             ::                  ?:         sizeof


++p -> p.operator++()
p++ -> p.operator++(int)
Posted by Triany
2011. 3. 9. 21:06

C에서는 출력양식에서 prinf("%2d", a);
이런 식의 출력양식이 있어서 출력할때 제법 깔끔했다.

하지만, C++언어로 들어온뒤
cout<<a;
식으로 출력할때 %d와 같은 출력 형식을 지정하지 않은 것은 편했지만, 예쁘게(?) 출력이 안되는게 고민이었다.
이때 해결책이 setw(int num) 함수다.ㅎ

setw(int num)
헤더 : #include <iomanip.h>

가령
cout<<setw(7)<<"Hey~"<<endl;
라고 입력하게 되면,
"Hey~   " 이렇게 3자리 공백과 함께 출력된다.

잘만 사용하면 제법 깔끔해 보이는 프로그래밍을 할 듯 싶다.
Posted by Triany
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. 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