250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/8.9] 클래스와 const, reference(&) 본문

C++/따배C++ 08강 객체지향 기초

[C++/8.9] 클래스와 const, reference(&)

polarcompass 2021. 10. 23. 07:05
728x90

함수 인자로 <const 생성자 &변수> 형태로 넣어주면 같은 메모리를 사용하므로 효율이 극대화 된다.

#include<iostream>
using namespace std;

class Something
{
public:
    int m_value = 0;

    Something(const Something& st_in)
    {
        m_value = st_in.m_value;
        cout << "Copy Constructor" << endl;
    }

    Something()
    {
        cout << "Constructor" << endl;
    }

    void setValue(int value) { m_value = value;}
    
    int  getValue() const // 함수 안쪽의 멤버 변수가 변하지 않는다는것을 표시
    { 
        return m_value;
    }
};
                         // 참조
void print(const Something &st) // <const 클래스 &변수> 형태로 넣어야 클래스
{      // 변수 주소               // 내부에서 복사 과정 없이 효율적으로 동작한다.
    cout << &st << endl;
    cout << st.getValue() << endl;
};

int main()
{
    const Something some; // object
    // some.setValue(3); 상수값 변환 불가, const로 고정해버렸기 때문임.

    // cout << some.getValue() << endl;

    cout << &some << endl;
    print(some);


    return 0;
}
#include<iostream>
#include<string>
using namespace std;

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

    const string& getValue() const 
    {   
        cout << "const version" << endl;
        return m_value;
    }

    string& getValue()
    {   
        cout << "non-const version" << endl;
        return m_value; 
    }
};

int main(int argc, char const *argv[])
{
    Something some;
    some.getValue() = 10; // non-const reference라 값 변환 가능.

    const Something some2;
    some2.getValue(); // const reference라 값 변환 불가능.

    return 0;
}
728x90