-
카테고리
-
세부 분야
프로그래밍 언어
-
해결 여부
미해결
대입연산자 오버로딩 리턴형
21.07.23 15:26 작성 조회수 303
1
클래스내에 deep copy를 하는 복사 생성자와
deep copy를 하는 대입연산자가 있다면
deep copy를 한다는 측면에서는 기능이 갔다고볼수있습니다.
대입연산자를 오버로드 할때 카피생성자 처럼
리턴형이 없이 void operator= (....) 해도
데이터를 복사하는 데에는 이상이 없는데
레퍼런스로 리턴해주는 이유라도있나요?
코드도 첨부합니다
class String
{
private:
char* m_data = nullptr;
unsigned m_length = 0;
public:
String()
{}
String(const char* source)
{
//assert(source);
m_length = strlen(source) + 1;
m_data = new char[m_length];
data_copy(source);
}
String(const String& source)
{
cout << "카피생성자" << endl;
deep_copy(source);
}
String& operator=(const String& source)
{
cout << "대입연산자" << endl;
if (m_data == source.m_data) return *this;
delete[] m_data;
deep_copy(source);
return *this;
}
void deep_copy(const String& source)
{
m_length = source.m_length;
if (source.m_data != nullptr)
{
m_data = new char[m_length];
data_copy(source.m_data);
}
else m_data = nullptr;
}
void data_copy(const char* source)
{
for (unsigned i = 0; i < m_length; ++i)
{
m_data[i] = source[i];
}
}
};
답변을 작성해보세요.
3
안소
2021.07.24
원래 대입연산자 자체가 리턴이 있는 연산자입니다.
a = b = 3
라는 식이 있다면 b = 3 라는 대입 연산식에서 b 를 리턴하기 때문에 이어서 a = b 를 할 수 있게 됩니다.
대입과 동시에 리턴을 하도록 return a = 2; 이런식으로 함수 코드를 짜기도 해요!
대입 연산자 오버로딩시 void 로 할지 리턴을 넣을지는 프로그래머 마음입니다. 그치만 대입연산자 자체가 원래 리턴이 있는 연산자이기 때문에 강의에서 코드를 저렇게 진행하신게 아닐까 싶네요~
답변 1