C++/C++ 복사 생성자, 복사 할당 연산자(Canonical form)

복사 생성자와 복사 할당 연산자(Canonical form)

재윤 2023. 12. 1. 13:01
반응형
  • C++의 Canonical form(정규형)을 따르게 되면 복사 생성자와 복사 할당 연산자를 꼭 기입을 해주어야한다.
  • Canonical form(정규형)이란?
    • C++98의 OCCF에 대해여 정리

Orthodox Canonical Class Form (OCCF)

정식 클래스 형식 OCCF는 아래 네 가지의 형태를 명시적으로 정의하여 선언하는 것을 가리킨다.

  • 기본 생성자
  • 기본 소멸자
  • 복사 생성자
  • 할당 연산자 오버로딩

예를 통해 살펴보자

Animal.hpp

#ifndef ANIMAL_HPP
# define ANIMAL_HPP

#include <iostream>

class Animal {
protected:
	std::string type;
public:
	Animal(void); //기본 생성자
	Animal(const Animal &obj); // 복사 생성자
	Animal& operator=(const Animal& obj); // 할당 연산자 오버로딩
	virtual ~Animal(void); // 기본 소멸자

	virtual void makeSound(void) const;
	std::string getType(void) const;
};

# endif

Animal.cpp

#include "Animal.hpp"

//기본 생성자
Animal::Animal(void)
{
	this->type = "animal";
	std::cout << "Animal Constructor called\\n";
}

//복사 생성자
Animal::Animal(Animal const &animal)
{
	*this = animal;
	std::cout << "Animal Constructor copy called\\n";
}

//기본 소멸자
Animal::~Animal()
{
	std::cout << "Animal Destructor called\\n";
}

//할당 연산자 오버로딩
Animal& Animal::operator=(Animal const &animal)
{

	if (this == &animal)
		return *this;
	this->type = animal.getType();
	std::cout << "Animal operator = " << type << " called\\n";
	return (*this);
}

std::string Animal::getType(void) const
{
	return (this->type);
}

void Animal::makeSound(void) const 
{
	std::cout << "Animal class can't make sound\\n";	
}

 

복사 생성자와 복사 할당 연산자 같이 쓰기

  • 복사 생성자에 *this = animal를 작성하면 할당 연산자 오버로딩을 불러와서 자동으로 자기 자신 대입을 막을 수 있으며, 복사도 가능하다.
//복사 생성자
Animal::Animal(Animal const &animal)
{
	*this = animal;
	std::cout << "Animal Constructor copy called\\n";
}

//할당 연산자 오버로딩
Animal& Animal::operator=(Animal const &animal)
{

	if (this == &animal)
		return *this;
	this->type = animal.getType();
	std::cout << "Animal operator = " << type << " called\\n";
	return (*this);
}

반응형

'C++ > C++ 복사 생성자, 복사 할당 연산자(Canonical form)' 카테고리의 다른 글

깊은 복사  (0) 2024.01.24
복사 할당 연산자  (0) 2023.12.01
복사 생성자  (0) 2023.12.01