클래스와 const

강형우·2022년 12월 13일
0

C++

목록 보기
10/10
post-thumbnail

객체 선언시 const

class Something
{
public:
	int m_value = 0;
    
    void setValue(int value) { m_value = value; }
    int getValue() { return m_value; }
}
int main()
{
	const Something something; //object는 상수. 바꿀 수 없다. 멤버 변수를 const로 만든것과 같은 의미
    something.setValue(3); // ❌ 에러! const라 바꿀 수 없는데 setValue는 안의 m_value를 바꾸려 하기에 에러
    
    // 값을 바꾸지 않고 그냥 가져오기만하는 getValue는 ?
    cout << something.getValue() << endl; // ❌ 에러!
    return 0;
}

컴파일러 판단시 m-value가 바뀐것인가 아닌가로 판단하는것이 아닌 멤버함수가 const인지 아닌지로 판단.

멤버 함수 뒤에 const가 붙어있을경우 사용 가능

class Something
{
public:
	int m_value = 0;
    
    /*void setValue(int value) const
    {
    	// const함수에서는 멤버의 값을 바꿀 수 없는데 m_value를 value로 바꾸려함.
        // 애초에 값을 바꾸려는 setValue에 const를 붙이는것이 모순
    	m_value = value; // ❌ 에러!
    }*/
    void setValue(int value) { m_value = value; }
    int getValue() const // const를 뒤에 붙이면 멤버함수가 const라고 선언
    { 
    // 멤버함수가 const라는것은 함수 안에서 멤버변수(m_value)를 바꾸는 행위를 하지 않는다라는 것을 확실하게 함
    	return m_value; 
    }
}
int main()
{
	const Something something; //object는 상수. 바꿀 수 없다. 멤버 변수를 const로 만든것과 같은 의미

    cout << something.getValue() << endl; // ✔️ 가능
    return 0;
}

복사 생성자

class Something
{
public:
	int m_value = 0;

    Something()
    {
    	cout << "생성자" << endl;
    }
    
    void setValue(int value)
    { 
    	m_value = value;
    }
    int getValue() const
    { 
    	return m_value; 
    }
}

void print(Something st) // print에선 Something st가 복사가 된다. 👈
{
	cout << st.m_value << endl;
}

int main()
{
	Something something;
    print(something); // print에 인자로 something이 주어지고 print함수로 가서 👆
    return 0;
}
  • 예상 출력 결과: 생성자가 2번 만들어지므로 생성자가 2번 출력되고, 0이 출력된다.

  • 실제 출력 결과

    생성자
    0

  • 주소를 찍어본다면 ?

class Something
{
public:
	int m_value = 0;

    Something()
    {
    	cout << "생성자" << endl;
    }
    
    void setValue(int value)
    { 
    	m_value = value;
    }
    int getValue() const // const를 뒤에 붙이면 멤버함수가 const라고 선언
    { 
    // 멤버함수가 const라는것은 함수 안에서 멤버변수(m_value)를 바꾸는 행위를 하지 않는다라는 것을 확실하게 함
    	return m_value; 
    }
}

void print(Something st) // print에선 Something st가 복사가 된다. 👈
{
	cout << &st << endl;

	cout << st.m_value << endl;
}

int main()
{
	Something something;
    cout << &something << endl;
    print(something); // print에 인자로 something이 주어지고 print함수로 가서 👆
    return 0;
}
  • 출력 결과: 주소는 2번 생기는데 생성자는 1번만 출력된다.

    생성자
    004FF82C
    004FF758
    0

  • 복사 constructor

class Something
{
public:
	int m_value = 0;
     // 여기에 복사 constructor이 숨겨져 있었음.
    Something(const Something& st_in) // copy constructor 이라고 부른다
    {
    	m_value = st_in.m_value;
        cout << "Copy constructor" << endl;
    }


    Something()
    {
    	cout << "생성자" << endl;
    }
    
    void setValue(int value)
    { 
    	m_value = value;
    }
    int getValue() const
    { 
    	return m_value; 
    }
}

void print(Something st) // 이런식으로 받게 되면 call by value로 복사가 이루어짐
{
	cout << &st << endl;

	cout << st.m_value << endl;
    // or
    cout << st.getValue() << endl;
}

int main()
{
	Something something;
    cout << &something << endl;
    print(something);
    return 0;
}
  • 출력 결과

    생성자
    00EFF870
    Copy constructor
    00EEF790

void print(const Something &st) // 일반 변수를 사용해서 인자로 보낼때
{
	cout << &st << endl;
    cout << st.getValue() << endl;
}
int main()
{
	Something something;
    print(something);
    return 0;
}
  • 출력 결과: 굉장히 효율적이다.

    생성자
    008FF7DC
    008FF7DC
    0

const 오버로딩

class Something
{
public:
    string m_value = "default";

    const string& getValue() const
    {
        cout << "const ver" << endl;
        return m_value; // const reference 리턴
    }

    string& getValue()
    {
        cout << "non-const version" << endl;
        return m_value; // nonconst reference 리턴
    }
}

int main()
{
    Something something1;
    something.getValue();   // string& getValue() 호출
    something.getValue() = 10; // ✔️ 가능

    const Something something2;
    something.getValue();  // const string& getValue() const 호출
    something2.getValue(); // ❌ 에러!
}
  • 출력 결과

    non-const ver
    const ver

0개의 댓글