" /> C++ 6주차 String과 객체, 참조 | BlackWerf's Blog
포스트

C++ 6주차 String과 객체, 참조

String

특징

  • C++의 표준 라이브러리로, 가변 길이 문자열
  • 문자열 연산 함수를 지원함(비교, 복사, 길이….)


사용 방법

  • **** 헤더 사용


    문자열 생성

    char형 문자 배열을 string 문자열로 생성하기

    1
    2
    3
    4
    5
    6
    
    int main()
    {
        char charArr[] = {'C', 'h', 'a', 'r', ' ', 'A', 's','e','m','b','l','e'};
        string charToString(charArr);
        cout << charToString << endl;
    }
    

    결과

    1
    
    Char Asemble
    


    문자열 입출력

    입력
    1
    2
    
    string 문자열이름;
    cin >> 문자열이름; //공백도 하나의 문자열로 입력받음
    


    출력
    1
    2
    
    string 문자열명;
    cout << 문자열명 << endl;
    


    숫자 변환

    Visaul C++ 2010 이상

    stoi(string 변수);

    • 예시)
    1
    2
    3
    
    string s = "1257";
    int n = stoi(s);
    cout << n << endl;
    

    결과

    1
    
    1257
    
    Visaul C++ 2010 이전

    atoi(string 변수);

    • 예시)
    1
    2
    3
    
    string s = "1257";
    int n = atoi(s);
    cout << n << endl;
    


    동적 생성

    1
    
    string *변수명 = new string("입력할 문자열");
    


    배열

    1
    
    string 변수명[크기];
    


    분리 및 합치기

    분리
    1
    
    string변수명.substr(시작위치, 문자 갯수);
    
    • 예시)

      1
      2
      3
      4
      5
      6
      7
      
      int main(){
      string s = "Text";
      string outText1 = s.substr(1, 2);
      cout << outText1 << endl;
      string outText2 = s.substr(2, 2);
      cout << outText2 << endl;
      }
      

      결과

      1
      2
      
      ex
      xt
      


    합치기
    1
    
    string변수1 + string변수2;
    
    • 예시)

      1
      2
      3
      4
      5
      6
      
      int main(){
      	string s1 = "Str";
      	string s2 = "Plus";
      	string result = s1 + s2;
      	cout << result << endl;
      }
      

      결과

      1
      
      StrPlus
      


    문자열 찾기와 교체

찾기
1
string변수명.find(찾을 단어, 검색을 시작할 문장의 시작지점);


교체
1
string변수명.replace(교체를 시작할 문장의 시작지점, 교체할 문자열의 길이, 교체할 문자);


함수호출

주소에 의한 객체 전달

  • 함수 호출 시, 객체의 주소를 전달함
    • 생성자와 소멸자가 실행되지 않음


객체의 치환과 함수 반환

객체의 치환

  • 객체 간에 치환 가능

  • 예시)

    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
    
    class Circle {
    private:
        int radius;
    public:
        Circle() {
            radius = 1;
        }
        Circle(int r) {
            radius = r;
        }
        int getRadius() {
            return radius;
        }
    };
      
      
    int main()
    {
        Circle c1(5);
        Circle c2(30);
        cout << "치환 전 c1 radius :" << c1.getRadius() << endl;
        cout << "치환 전 c2 radius : " << c2.getRadius() << endl;
        c1 = c2;
        cout << "치환 후 c1 radius : " << c1.getRadius() << endl;
        cout << "치환 후 c2 radius : " << c2.getRadius() << endl;
    }
    

    결과

    1
    2
    3
    4
    
    치환 전 c1 radius :5
    치환 전 c2 radius : 30
    치환 후 c1 radius : 30
    치환 후 c2 radius : 30
    


  • 예시 코드에서, c1은 radius의 값이 5, c2는 30을 가지고 있다.

    치환 전에는 c1와 c2의 radius의 값이 각자 생성되며 초기화 된 값인 5와 30의 값을 가진다.

    c1=c2; 이용해 c1에 c2 값을 치환 한 이후에는, c1이 c2와 같이 30의 값을 가진다.


객체의 반환

  • 객체의 함수 반환
  • 예시
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
class Circle {
private:
    int radius;
public:
    Circle() {
        radius = 1;
    }
    Circle(int r) {
        radius = r;
    }
    int getRadius() {
        return radius;
    }
};

Circle getCircle() {
    Circle tmpCircle(30);
    return tmpCircle;
}

int main()
{
    Circle c1(5);
    cout << "객체 반환 전 c1의 radius >>" << c1.getRadius() << endl;
    c1 = getCircle();
    cout << "객체 반환 후 c1의 radius >>" << c1.getRadius() << endl;
}

결과

1
2
객체 반환 전 c1의 radius >>5
객체 반환 후 c1의 radius >>30


  • 예시 코드에서는 5의 값을 가진 c1 객체와 getCircle 객체가 존재한다.

​ getCircle 객체는 내부에 tmpCircle이라는 radius 값이 30인 tmpCircle 객체를 반환한다

​ c1 = getCircle()를 이용하여 c1에 getCircle 객체의 함수를 반환하면 c1이 getCircle 객체 내의 tmpCircle의 radius 값인 30을 가지게 된다.


참조

변수의 참조

  • 형식: &변수명 = 참조변수명;

  • 예시)

    int main(){
          
    int a = 20;
    int &refv = a;
          
        cout << "a >>" << a << endl; 
            cout << "refv >>" << refv << endl;
    }
    

    결과

    1
    2
    
    a >>20
    refv >>20
    


    • 변수 a는 20으로 선언되며 초기화 된다.

      refv는 변수 a를 참조하며 생성되며 20으로 값이 초기화 된다.


객체의 참조

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
class Circle {
private:
    int radius;
public:
    Circle() {
        radius = 1;
    }
    Circle(int r) {
        radius = r;
    }
    int getRadius() {
        return radius;
    }
    int setRadius(int radius) {
        return this->radius = radius;
    }
};


int main()
{
    Circle circle;
    Circle& refCircle = circle;
    refCircle.setRadius(20);
    cout << "circle의 radius: " << circle.getRadius() << endl;
    cout << "refCircle radius: " << refCircle.getRadius() << endl;
}

결과

1
2
circle의 radius: 20
refCircle radius: 20


  • refCircle는 같은 Circle 객체인 circle를 참조한다.

    circle은 매개변수 없이 인스턴스화 되어, radius의 값은 1이다.

    refCircle에서 setRadius(20)를 실행하면서 circle도 값이 업데이트 되며, refCircle과 circle의 radius가 모두 20이 되었다.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.