728x90
클래스 멤버변수 초기화 리스트 사용 방법
- 생성자 괄호() 뒤에 콜론(:)으로 표기한다.
- 초기화 할 멤버 변수들을 쉼표로 구변하여 표기한다.
- 소괄호()를 이용해서 멤버 변수를 초기화한다.
사용법
예시1)
#include<iostream>
#include<string>
using namespace std;
class Car
{
private:
string name;
int number;
bool inSuv;
public:
Car() : name("kdy"), number(1212), inSuv(false)
{
cout << "생성자 호출" << endl;
}
~Book(){
cout << "소멸자 호출" << endl;
}
};
Car의 멤버변수 name, number, inSuv를 호출할 때 바로 "kdy", 1212, false로 초기화 시켜준다.
예시2)
#include<iostream>
#include<string>
using namespace std;
class Person
{
private:
int age_;
string str_;
public:
Person() : age_(0), str_("kdy")
{
cout << "디폴트 생성자 호출" << endl;
}
Person(int age, string str) : age_(age), str_(str)
{
cout << "age, str 생성자 호출" << endl;
}
Person& operator = (const Person& rsh)
{
this->age_ = rsh.age_;
this->str_ = rsh.str_;
cout << "대입연산자 호출" << endl;
return *this;
}
void printAll(){
cout << "age : " << age_ << endl;
cout << "str : " << str_ << endl;
}
};
int main(){
cout << "\n=====\n";
Person p1(10, "aa");
p1.printAll();
cout << " /n=====/n";
Person p2 = {20, "bb"};
p2.printAll();
cout << "\n=====\n";
Person p3 = Person(30, "cc");
p3.printAll();
cout << "\n=====\n";
Person p4;
p4 = Person(40, "dd");
p4.printAll();
return 0;
}
위의 코드를 실행해보면 결과값이 아래처럼 나온다.
멤버 초기화 리스트를 사용한 것과 사용하지 않은 것의 차이점
"초기화를 바로 하는 것 vs 나중에 대입으로 값을 초기화 해주는 것"
"생성 시 초기화 vs 생성 후 초기화"
생성 후 초기화
class Test{
int a, b;
public:
Test(int x, int y) { a = x; b = y; }
};
생성자 내부에서 클래스의 멤버변수들을 초기화했다.
일반적인 생성자를 이용하여 초기화하는 방법이다.
생성 시 초기화
class Test{
int a, b;
public:
Test(int x, int y) : a(x), b(y) { }
};
멤버 초기화 리스트(member initialization list)를 이용한 초기화 방법이다.
C++ 멤버 초기화 리스트를 꼭 사용해야 하는 경우
선언과 동시에 초기화 해야하는 변수들이 있을 때 사용
- 상수(const) 멤버 변수 초기화
- reference 멤버 변수 초기화
- 멤버 객체 초기화
- 상속 멤버 변수 초기화
상수 멤버 변수 초기화
틀린 방법
class Test{
const int test;
Test(int x) {
test = x;
}
};
const value는 위와 같이 초기화하면 에러가 난다. 그래서 선언과 동시에 초기화를 해야 하므로 멤버 초기화 리스트를 사용한다.
옳은 방법
class Test{
const int test;
Test(int x) : test(x){ }
};
reference 멤버 변수 초기화
class Test{
int& test;
Test(int x) : test(x) { }
};
멤버 객체 초기화
클래스 내에 객체 멤버가 있는 경우 해당 객체의 생성자가 호출되어야 한다.
이 경우에도 초기화리스트의 사용이 강제된다.
class Test1
{
int x;
int y;
public:
Test1(int a, int b){
x = a;
y = b;
}
};
class Test2
{
int test;
public:
Test1 t;
Test2(int x, int a, int b) : t(a, b){
test = x;
}
};
상속 멤버 변수 초기화
class Parent
{
public:
int x,y;
Parent(int i, int j){
x = i;
y = j;
}
};
class Test : public Parent
{
public:
int test;
Test(int i, int j, int k) : Parent(i, j)
{
test = k;
}
};
위의 멤버 객체 초기화와 거의 동일하다.
'C,C++' 카테고리의 다른 글
C++ 스마트 포인터 ( shared_ptr, make_shared ) (0) | 2022.04.10 |
---|---|
C++ 범위 지정 연산자(::)와 namespace (0) | 2022.04.10 |
C++ 가상 함수(virtual function) (0) | 2022.04.09 |
c++에서 string 클래스를 이용한 문자열 사용 ( getline() ) (0) | 2022.03.12 |
배열의 크기를 넘어가서 사용할 경우 (0) | 2022.02.14 |