20141030 (C++ string class, Template)

169일차









----------

C++

----------




------- string class


문자열과 관련된 class이다.

다음 예제 확인


예제)

#include <iostream>
#include <string>
using namespace std;

int main(void)
{
  string str1="I like ";
  string str2="string class";
  string str3=str1+str2;

  cout<<str1<<endl;
  cout<<str2<<endl;
  cout<<str3<<endl;

  str1+=str2;
  if(str1==str3)   
    cout<<"동일 문자열!"<<endl;
  else
    cout<<"동일하지 않은 문자열!"<<endl;

  string str4;
  cout<<"문자열 입력: ";
  cin>>str4;
  cout<<"입력한 문자열: "<<str4<<endl;
  return 0;
}

결과


위의 결과를 보면 알수 있듯이 string class를 사용하면

객체끼지 덧셈으로 문자열을 합칠 수도 있다.




이런 class가 어떻게 구현되는지 직접 구현해 보기로 한다.


예제)

#include <iostream>
#include <cstring>

using namespace std;

class String
{
  private:
    int len;
    char * str;

  public:
    String();
    String(const char * s);
    String(const String& s);
    ~String();
    String& operator=(const String& s);
    String& operator+=(const String& s);
    bool operator==(const String& s);
    String operator+(const String& s);

    friend ostream& operator<<(ostream& os, const String& s);
    friend istream& operator>>(ostream& os, const String& s);
};

String::String()
{
  len=0;
  str=NULL;
}

String::String(const char* s)
{
  len=strlen(s)+1;
  str=new char[len];
  strcpy(str, s);
}

String::String(const String& s)
{
  len=s.len;
  str=new char[len];
  strcpy(str, s.str);
}

String::~String() 
{
  if(str!=NULL)
    delete []str; 
}

String& String::operator= (const String& s)
{
  if(str!=NULL)
    delete []str;
  len=s.len;
  str=new char[len];
  strcpy(str, s.str);
  return *this;
}

String& String::operator+= (const String& s)
{
  len+=(s.len-1);
  char* tempstr=new char[len];
  strcpy(tempstr, str);
  strcat(tempstr, s.str);

  if(str!=NULL)
    delete []str;
  str=tempstr;
  return *this;
}

bool String::operator== (const String& s)
{
  return strcmp(str, s.str) ? false : true;
}

String String::operator+ (const String& s)
{
  char* tempstr=new char[len+s.len-1];
  strcpy(tempstr, str);
  strcat(tempstr, s.str);
  
  String temp(tempstr);
  delete []tempstr;
  return temp;
}

ostream& operator<< (ostream& os, const String& s)
{
  os<<s.str;
  return os;
}

istream& operator>> (istream& is, String& s)
{
  char str[100];
  is>>str;
  s=String(str);
  return is;
}

int main()
{
  String str1 = "I like ";
  String str2 = "string class";
  String str3 = str1 + str2;

  cout << str1 << endl;
  cout << str2 << endl;
  cout << str3 << endl;

  str1 += str2;
  if(str1 == str3)
  {
    cout << "동일한 문자열" << endl;
  }
  else
  {
    cout << "다른 문자열" << endl;
  }

  String str4;
  cout << "문자열 입력 : ";
  cin >> str4;
  cout << "입력한 문자열 : " << str4 << endl;

  return 0;
}

결과



이렇게 구현할 수 있다.










------- Template (템플릿)


모형자라는 뜻이 담겨있는데 어떤 틀을 만드는 것이다.

아래 예제를 참고


예제)

#include <iostream>
#include <string>

using namespace std;

template <typename T>
T Add(T num1, T num2)
{
  return num1+num2;
}

int main()
{
  cout << Add<int>(1520<< endl;
  cout << Add<double>(0.51.0<< endl;
  cout << Add<int>(3.12.2<< endl;
  cout << Add<double>(5.410.15<< endl;
  cout << Add<string>("Hi"" world"<< endl;

  return 0;
}

결과


template <typename "타입 이름">

이 타입을 적용할 변수 앞에 "타입 이름"을 적어서 사용한다.


이런식으로 다른 타입의 오버로딩 함수를 정의하지 않아도 짧게 코드를 작성할 수 있다.

컴파일 과정 중에 다른 타입의 함수를 컴파일러가 코드를 작성하여 넣어주기 때문에

프로그램의 크기가 더 작아지는 것은 아니다.





함수와 인수 사이에 <타입>을 넣어야 하는데, 만약 넣지 않으면 묵시적 변환이 일어난다.

다음 예제 확인


예제)

#include <iostream>
#include <string>

using namespace std;

template <typename T>
T Add(T num1, T num2)
{
  return num1+num2;
}

int main()
{
  cout << Add(1520<< endl;
  cout << Add(0.51.0<< endl;
  cout << Add(3.12.2<< endl;
  cout << Add(5.410.15<< endl;

  //cout << Add("Hi", " world") << endl;
  string obj1("Hi");
  string obj2(" world");
  cout << Add(obj1, obj2) << endl;

  return 0;
}

결과


위에서 보듯이 <타입>을 생략하면 뒤에 오는 타입에 맞게 묵시적으로 변환되기 때문에

의도치 않은 변환이 일어날 수도 있다.




만약 오버로딩 함수와 템플릿 함수를 함께 정의해 놓았을 경우는 어떻게 될까?

아래 예제 참고

예제)

#include <iostream>

using namespace std;

template <typename T>
T Add(T num1, T num2)
{
  cout << "T Add(T num1, T num2)" << endl;
  return num1 + num2;
}

int Add(int num1, int num2)
{
  cout << "Add(int num1, int num2)" << endl;
  return num1 + num2;
}

double Add(double num1, double num2)
{
  cout << "Add(double num1, double num2)" << endl;
  return num1 + num2;
}

int main()
{
  cout << Add(57<< endl;
  cout << Add(3.77.5<< endl;
  cout << Add<int>(57<< endl;
  cout << Add<double>(3.77.5<< endl;

  return 0;
}

결과


이렇듯 겹치게 되면 확실하게 해야한다.








설정

트랙백

댓글