#6 [c++]string, 매개 변수 전달 방법, 참조

정상준·2022년 10월 27일
0

c++

목록 보기
3/25

C++ 문자열 모듈

  • C스트링 - char에 배열 사용(공간 낭비 발생)
  • string 클래스
    • C++ 표준 라이브러리 상요
    • <string> 헤더 사용 ( #include)
    • 가변길이 문자열
    • 문자열 연산을 지원하는 함수 지원:비교, 복사, 길이 등

string을 이용하여 숫자 변환

string s = "1234";
int n = stoi(s); //문자열이 숫자로 변환되어 return;

string 객체의 동적 생성(동적 생성은 heap영역에 생성)

string *p = new string("Hello") //string 객체 동적 생성

cout << *p; //Hello 출력
p -> append(" c++");
cout << *p; // Hello c++ 출력

delete p; //string 객체 반환

예제 1.(사전에서 가장 뒤에 나오는 문자찾기)

#include <iostream>
#include<string>
using namespace std;


int main() {
	string names[5]; //문자열 배열 선언

	for (int i = 0; i < 5; i++) {
		cout << "이름>>";
		getline(cin, names[i], '\n'); //엔터 만나기 전까지 문자열 입력받음
	}

	string latter = names[0];

	for (int i = 1; i < 5; i++) {
		if (latter < names[i]) { //사전 순으로 정렬
			latter = names[i];
		}
	}

	cout << "가장 뒤에 나오는 이름은 " << latter;
}

예제 2.(문자열 맨 앞 문자를 맨 뒤로 보내는 것을 원래의 문자열 나올때까지 반복하기)

#include <iostream>
#include <string>
using namespace std;


int main() {
	string s;

	cout << "문자열을 입력하세요" << endl;
	getline(cin, s, '\n');
	int len = s.length();

	for (int i = 0; i < len; i++) {
		string first = s.substr(0, 1); //맨 앞의 문자 1개를 문자열로 분리
		string sub = s.substr(1, len - 1); //나머지 문자들을 문자열로 분리
		s = sub + first; //두 문자열 연결하여 새로운 문자열로 만듬
		cout << s << endl;
	}
}

예제3. (문자열 찾아서 교체하기)

#include <iostream>
#include <string>
using namespace std;


int main() {
	string s;
	cout << "여러 줄의 문자열을 입력하세요. 입력의 끝은 &문자입니다." << endl;

	getline(cin, s, '&');//문자열 입력
	cin.ignore(); //&뒤에 enter키 제거

	string f, r;
	cout << endl << "find: ";
	getline(cin, f, '\n');
	cout << "replace: ";
	getline(cin, r, '\n');

	int startIndex = 0;
	while (true)
	{
		int fIndex = s.find(f, startIndex); //startIndex부터 문자열 f검색
		if (fIndex == -1) {
			break;
		}
		s.replace(fIndex, f.length(), r); //fIndex부터 문자열 f의 길이만큼 문자열 r로 변경
		startIndex = fIndex + r.length();
	}

	cout << s << endl;
}

매개 변수 전달 방법

  • 값에 의한 호출 : call by value
  • 주소에 의한 호출 : call by address
  • 참조에 의한 호출 : call by reference

값에 의한 호출 : 호출하는 코드에서 넘어온 값을 매개 변수에 복사함(스택이용)

#include <iostream>
#include <string>
using namespace std;

/* swap에 의해 값 변경되지 않음 */

void swap(int a, int b) {
	int tmp;

	tmp = a;
	a = b;
	b = tmp;
}

int main() {
	int m = 9, n = 2;

	swap(m, n);
	cout << m << ' ' << n;
}

주소에 의한 호출 : 값을 가지고 있는 변수의 주소를 포인터 변수를 통해 전달

#include <iostream>
#include <string>
using namespace std;

/* 스왑에 의해 m, n 값 교환 */

void swap(int *a, int *b) {
	int tmp;

	tmp = *a;
	*a = *b;
	*b = tmp;
}

int main() {
	int m = 9, n = 2;

	swap(&m, &n);
	cout << m << ' ' << n;
}

참조에 의한 호출 : 참조매개 변수의 이름만 사용하고 별도 공간이 생기지 않음

값에 의한 객체 전달

  • 값에 의한 호출
    • 함수의 매개 변수로 객체 생성
    • 생성자는 호출되지 않음 (생성자 호출로인한 객체의 초기화 방지)
    • 함수 종료시 소멸자 호출
    • 생성자와 소멸자의 비대칭 실행
#include <iostream>
#include <string>
using namespace std;

/* 객체 전달시 생성자는 호출 x 소멸자는 호출 o */
/* 출력 :
생성자 실행 radius = 30
소멸자 실행 radius = 31
30
소멸자 실행 radius = 30
*/

class Circle {
private:
	int radius;
public:
	Circle() :Circle(1) {};
	Circle(int r);
	~Circle() {
		cout << "소멸자 실행 radius = " << radius << endl;
	}
	double getArea() { return 3.14 * radius * radius; }
	int getRadius() { return radius; }
	void setRadius(int radius) {
		this->radius = radius;
	}
};

Circle::Circle(int radius) {
	this->radius = radius;
	cout << "생성자 실행 radius = " << radius << endl;
}

void increase(Circle c) {
	int r = c.getRadius();
	c.setRadius(r + 1);
}

int main() {
	Circle donut(30);
	increase(donut);
	cout << donut.getRadius() << endl;
}

주소에 의한 객체 전달

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

#include <iostream>
#include <string>
using namespace std;

/* 출력 
생성자 실행 radius = 10
20
소멸자 실행 radius = 20
*/

class Circle {
private:
	int radius;
public:
	Circle() :Circle(1) {};
	Circle(int r);
	~Circle() {
		cout << "소멸자 실행 radius = " << radius << endl;
	}
	double getArea() { return 3.14 * radius * radius; }
	int getRadius() { return radius; }
	void setRadius(int radius) {
		this->radius = radius;
	}
};

Circle::Circle(int radius) {
	this->radius = radius;
	cout << "생성자 실행 radius = " << radius << endl;
}

void increase(Circle *p) {
	int tmp;
	tmp = p->getRadius();
	p->setRadius(tmp + 10);
}

int main() {
	Circle ring(10);
	increase(&ring);
	cout << ring.getRadius() << endl;
}

객체의 지환과 함수 반환

#include <iostream>
#include <string>
using namespace std;

/* 출력
생성자 실행 radius = 10
생성자 실행 radius = 1
3.14
314
생성자 실행 radius = 30
소멸자 실행 radius = 30
소멸자 실행 radius = 30
2826
소멸자 실행 radius = 30
소멸자 실행 radius = 10
*/

class Circle {
private:
	int radius;
public:
	Circle() :Circle(1) {};
	Circle(int r);
	~Circle() {
		cout << "소멸자 실행 radius = " << radius << endl;
	}
	double getArea() { return 3.14 * radius * radius; }

	void setRadius(int radius) {
		this->radius = radius;
	}
};

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

Circle::Circle(int radius) {
	this->radius = radius;
	cout << "생성자 실행 radius = " << radius << endl;
}

int main() {
	Circle c1(10);
	Circle c2;
	cout << c2.getArea() << endl;
	c2 = c1;
	cout << c2.getArea() << endl;
	c2 = getCircle();
	cout << c2.getArea() << endl;
}

변수의 참조

형식

  • &변수명 = 참조변수명;
  • &refb = b;
#include <iostream>
#include <string>
using namespace std;

/* 출력
a       b       refb
1       5       5
1       2       2
1       20      20
*/

int main() {
	cout << "a" << '\t' << "b" << '\t' << "refb" << endl;
	int a = 1;
	int b = 2;
	int& refb = b;
	b = 4;
	refb++; //b, refb == 5
	cout << a << '\t' << b << '\t' << refb << endl;

	refb = a; // b, refb == 1
	refb++; // b, refb == 2
	cout << a << '\t' << b << '\t' << refb << endl;

	int* p = &refb;
	*p = 20; //b, refb == 20
	cout << a << '\t' << b << '\t' << refb << endl;
}
profile
안드로이드개발자

0개의 댓글