초기화 리스트 __ initialization list

😎·2022년 11월 24일
0

CPP

목록 보기
5/46

클래스 초기와 방법

화살표 연산자 방식으로 초기화하는 방법도 있지만, 객체 생성 시 콜론으로 초기화를 함께하는 방법도 있다.

  • 줄 수가 줄어듬

  • 객체의 생성과 초기화가 한 번에 이루어짐


화살표 연산자 방식

Sample1::Sample1(char p1, int p2, float p3) {
    std::cout << "Constructor called" << std::endl;

    this->a1 = p1;
    std::cout << "this->a1 = " << this->a1 << std::endl;

    this->a2 = p2;
    std::cout << "this->a2 = " << this->a2 << std::endl;

    this->a3 = p3;
    std::cout << "this->a3 = " << this->a3 << std::endl;
    
    return;
}

초기화 리스트 방식

Sample2::Sample2(char p1, int p2, float p3) : a1(p1), a2(p2), a3(p3) {
    std::cout << "Constructor called" << std::endl;
    
    std::cout << "this->a1 = " << this->a1 << std::endl;
    std::cout << "this->a2 = " << this->a2 << std::endl;
    std::cout << "this->a3 = " << this->a3 << std::endl;
    
    return;
}

참고 자료


코드

  • main.c
#include "Sample1.class.hpp"
#include "Sample2.class.hpp"
#include <iostream>

int main() {
    Sample1 instance1('a', 45, 4.2f);
    Sample2 instance2('z', 13, 3.14f);

    return 0;
}
  • Simple1.class.cpp
#include "Sample1.class.hpp"
# include <iostream>

Sample1::Sample1(char p1, int p2, float p3) {
    std::cout << "Constructor called" << std::endl;

    this->a1 = p1;
    std::cout << "this->a1 = " << this->a1 << std::endl;

    this->a2 = p2;
    std::cout << "this->a2 = " << this->a2 << std::endl;

    this->a3 = p3;
    std::cout << "this->a3 = " << this->a3 << std::endl;
    
    return;
}

Sample1::~Sample1(void) {
    std::cout << "Destructor called" << std::endl;
    return ;
}
  • Simple1.class.hpp
#ifndef SAMPLE1_CLASS_H
# define SAMPLE1_CLASS_H

class Sample1 {

public:
    char a1;
    int a2;
    float a3;

    Sample1(char p1, int p2, float p3);
    ~Sample1(void);

};

#endif
  • Simple2.class.cpp
#include "Sample2.class.hpp"
# include <iostream>

Sample2::Sample2(char p1, int p2, float p3) : a1(p1), a2(p2), a3(p3) {
    std::cout << "Constructor called" << std::endl;
    
    std::cout << "this->a1 = " << this->a1 << std::endl;
    std::cout << "this->a2 = " << this->a2 << std::endl;
    std::cout << "this->a3 = " << this->a3 << std::endl;
    
    return;
}

Sample2::~Sample2(void) {
    std::cout << "Destructor called" << std::endl;
    return ;
}
  • Simple2.class.hpp
#ifndef SAMPLE2_CLASS_H
# define SAMPLE2_CLASS_H

class Sample2 {

public:
    char a1;
    int a2;
    float a3;

    Sample2(char p1, int p2, float p3);
    ~Sample2(void);

};

#endif

profile
jaekim

0개의 댓글