[열혈 c++ 프로그래밍] ch5

hyng·2023년 3월 13일
0

열혈 c++ 프로그래밍을 보고 요약정리합니다.

5-1 복사 생성자와의 첫 만남

  • c++ 에서 지원하는 초기화 방식
    int num = 20;
    int num(20);
  • 객체의 생성으로 대입
    SoSimple sim1(15, 20);
    SoSimple sim2 = sim1;
  • SoSimple sim2 = sim1;
    • SoSimple sim2(sim1); // 묵시적 변환이 되어서 객체가 생성되는 것
    • sim1을 인자로 받을 수 있는 생성자의 호출을 통해서 객체생성을 완료한다.
    • 이때 호출되는 생성자를 복사 생성자라고 한다.
    • 복사 생성자를 정의하지 않으면 디폴트 복사 생성자가 자동으로 삽입된다.
  • 복사 생성자의 묵시적 호출을 막기 위해서 explicit 키워드를 사용할 수 있다.
    explicit SoSimple(const SoSimple &copy) : num1(copy.num1), num2(copy.num2) 
    {
    		//empty!!
    }
  • 전달인자가 하나인 생성자가 있다면, 이 역시 묵시적 변환이 발생한다.
    
    AAA obj = 3; //AAA obj(3) 으로 변환
    

5-2 깊은 복사와 얕은 복사

  • 디폴트 복사 생성자는 멤버 대 멤버의 단순 복사를 진행하기 때문에 복사의 결과로 하나의 문자열을 두 개의 객체가 동시에 참조하는 꼴을 만들어버린다.
  • 깊은 복사를 위한 복사 생성자 정의
    Person(const Person & person)
        {
            int len = ::strlen(person.name) + 1;
            name = new char[len];
            strcpy(name, person.name);
            age = person.age;
        }

5-3 복사 생성자의 호출시점

  • 복사 생성자의 호출시점
    • 기존에 생성된 객체를 이용해서 새로운 객체를 초기화하는 경우
    • call-by-value 방식의 함수 호출 과정에서 객체를 인자로 전달하는 경우
    • 객체를 반환하되 참조형으로 반환하지 않는 경우
  • 메모리 공간의 할당과 초기화가 동시에 일어나는 상황
    int num1 = num2;
    • num1이라는 이름의 메모리 공간을 할당과 동시에 num2에 저장된 값으로 초기화시키는 문장이다.

      int SimpleFunc(int n) 
      {
         ...
      }
      int main(void) 
      {
      	int num = 10;
      	SimpleFunc(num);
      }
    • SimpleFunc 함수가 호출되는 순간에 매개변수 n이 할당과 동시에 변수 num에 저장되어 있는 값으로 초기화된다.

      int SimpleFunc(int n)
      {
         ...
      	 return n;
      }
      
      int main(void)
      {
         int num = 10;
      	 cout << SimpleFunc(num) << endl;
      }
    • 반환하는 순간 메모리 공간이 할당되면서 동시에 초기화된다.

  • 임시 객체는 다음 행으로 넘어가면 바로 소멸되어 버리지만 참조자에 참조되는 임시 객체는 바로 소멸되지 않는다.
    Temporary(10));
    const Temporary &ref = Temporary(300); //바로 소멸되지 x
  • OOP 단계별 프로젝트 굵은 글씨는 요구사항
    • 복사 생성자를 정의

      class Account{
      private:
          int id;
          int balance;
          char *name;
          Account(int id, int balance, char *name) {
              this->id = id;
              this->balance = balance;
              this->name = new char[::strlen(name) + 1];
              ::strcpy(this->name, name);
          }
      public:
          Account() {
      
          }
          
          Account(const Account & account)
          {
              this->id = account.id;
              this->balance = account.balance;
              this->name = new char[strlen(account.name) + 1];
              strcpy(this->name, account.name);
          }
          static Account Of(int _id, int _balance, char* _name) {
              return Account(_id, _balance, _name);
          }
          bool IsSame(int id) {
              return this->id == id;
          }
          void Deposit(int money) {
              this->balance += money;
          }
      
          void Withdraw(int money) {
              if (this->balance < money) {
                  cout << "잔액부족\n";
                  return;
              }
              this->balance -= money;
              cout << "출금완료\n";
          }
          void ShowInfo() {
              cout << "계좌ID: " << id << "\n";
              cout << "이 름: " << name << "\n";
              cout << "잔 액: " << balance << "\n";
          }
          Account* Copy() {
              return new Account(this->id, this->balance, this->name);
          }
      };
profile
공부하고 알게 된 내용을 기록하는 블로그

0개의 댓글