C++
3. Operator Overloading Function
튀김족발
2022. 12. 14. 20:53
C++이나 C#에서 string을 정의 및 연산을 할때 사용하는 명령어를 간단하게 만들어 보자.
보통 문자열 데이터를 선언할 때
string s = "hello";
이런식으로 선언 할 것이다. 이렇게 선언하는 방법을 만들어보자.
class string
{
public:
string(const char* s = nullptr)
{
if (s == nullptr)
{
buffer[0] = NULL;
}
else
{
strcpy_s(buffer, s);
}
}
const char* c_str() const
{
return buffer;
}
private:
char buffer[100];
};
(임시로 문자열 최대 크기는 100으로 잡아놨다.) 이런식으로 선언 한다. 이렇게 하고 위의 명령어를 실행 하면 hello 가 s에 할당 됐을 것이다.
그럼 이제 다음 연산을 만들어보자
보통 두개 이상의 문자열을 붙일때
string s = hello;
s = s + " world";
이런식으로 만들 것이다. 한번 만들어보자
class string
{
public:
string(const char* s = nullptr)
{
if (s == nullptr)
{
buffer[0] = NULL;
}
else
{
strcpy_s(buffer, s);
}
}
const char* c_str() const
{
return buffer;
}
string& add(const char* right)
{
string temp = *this;
strcat_s(temp.buffer, right);
return temp;
}
private:
char buffer[100];
};
일단, 간단하게 add함수로 만들었다. 이렇게 만들었다면,
string s = hello;
s.add(" world");
이런식으로 호출 할 수 있을것이다. 하지만, 매번 함수를 호출하기에는 불편하다. 그래서 C++에서 제공하고 있는 연산자 재정의 명령어인 operator를 사용할 것이다.
class string
{
public:
string(const char* s = nullptr)
{
if (s == nullptr)
{
buffer[0] = NULL;
}
else
{
strcpy_s(buffer, s);
}
}
const char* c_str() const
{
return buffer;
}
string& operator +(const char* right)
{
string temp = *this;
strcat_s(temp.buffer, right);
return temp;
}
string& operator =(const string& other)
{
memcpy(buffer, other.buffer, sizeof(buffer));
return *this;
}
private:
char buffer[100];
};
다음과 같이 operator를 활용해서 +와 =를 재정의 한다.
이렇게 재정의하면
string s = "hello";
s.operator+(" world").operator+("\r\n");
이렇게나
string s = "hello";
s = s + " world";
이렇게 우리가 흔히 사용하는 방식으로 사용할 수 있다.
하지만 여기에는 문제가 있다.
string t;
t = "hello " + s;
이런식으로 사용할 수 없다. 왜냐하면 + 연산자에는 반대로 하는 연산자가 없기 때문이다. 따라서 새로 정의를 해줘야 한다.
class string
{
friend string operator+(const char* left, const string& right);
public:
string(const char* s = nullptr)
{
if (s == nullptr)
{
buffer[0] = NULL;
}
else
{
strcpy_s(buffer, s);
}
}
const char* c_str() const
{
return buffer;
}
string& operator +(const char* right)
{
string temp = *this;
strcat_s(temp.buffer, right);
return temp;
}
string& operator =(const string& other)
{
memcpy(buffer, other.buffer, sizeof(buffer));
return *this;
}
private:
char buffer[100];
};
string operator+(const char* left, const string& right)
{
string t = left;
strcat_s(t.buffer, right.buffer);
return t;
}
이런식으로 friend를 사용해서 클래스 내부에 있는 private를 접근할 수있게 만들고 재정의를 해준다.
그리고 이 전에 안되던 명령어를 사용하면 사용이 가능해진다.