언어는 과-학인가요?/C++

Namespace (이름공간)/ String

이원자 탄소 2020. 10. 10. 12:57
728x90

이름공간(namespace)

- 이름을 붙여놓은 공간

- 특정 영역에 이름을 붙여주기 위한 문법적 요소

- 전역 함수나 변수의 유효범위에 이름을 붙여 분할시켜 중복(충돌)을 방지

 

#include <iostream>

namespace firstAdd {
	void add() {
		std::cout << "첫번째 공간이름 firstAdd 의 add함수를 출력" << std::endl;
	}
}

namespace secondAdd {
	void add() {
		std::cout << "두번째 공간이름 secondAdd 의 add함수를 출력" << std::endl;
	}
}

int main()
{
	firstAdd::add();
	secondAdd::add();
	
	return 0;
}

 

스코프 연산자 (::)

- 변수나 함수의 유효범위 = scope(스코프)

- 유효 범위 안에 같은 이름을 가진 변수나 함수가 있을땐 스코프 연산자를 사용한다

- 전역변수나 함수/오브젝트에 접근하는 우선순위 변경 가능

 

순서 바꿔서 출력도 ㄱㄴ

#include <iostream>

namespace firstAdd {
	void add();
}

namespace secondAdd {
	void add();
}

int main()
{
	firstAdd::add();
	secondAdd::add();

	return 0;
}


void firstAdd::add() {
	std::cout << "첫번째 공간이름 firstAdd 의 add함수를 출력" << std::endl;
}



void secondAdd::add() {
	std::cout << "두번째 공간이름 secondAdd 의 add함수를 출력" << std::endl;

}

 

이름공간의 중첩

 

#include <iostream>

namespace Parent {
	int number = 1;

	namespace SonOne {
		int number = 2;
	}

	namespace SonTwo {
		int number = 3;
	}
}

int main() {
	std::cout << Parent::number << std::endl;
	std::cout << Parent::SonOne::number << std::endl;
	std::cout << Parent::SonTwo::number << std::endl;

	return 0;

}

 

using으로 전역 이름공간으로 지정하기

#include <iostream>

using namespace std;

namespace firstAdd {
	void add();
}

namespace secondAdd {
	void add();
}

using namespace firstAdd;//전역으로 오픈시켜놈

int main()
{
	add();
	secondAdd::add();

	return 0;
}


void firstAdd::add() {
	std::cout << "첫번째 공간이름 firstAdd 의 add함수를 출력" << std::endl;
}



void secondAdd::add() {
	std::cout << "두번째 공간이름 secondAdd 의 add함수를 출력" << std::endl;

}

 

오브젝트에 접근하는 우선순위 변경

#include <iostream>

using namespace std;

int number = 100;

int main() {
	int number = 20;
	cout << number << endl;
	number += 20;
	::number += 50;
	cout << "지역변수 num출력 -> " << number << endl;
	cout << "지역변수 ::num출력 -> " << ::number << endl;

	return 0;

}

1. 지역변수 number출력

2. 지역변수에 20 더해서 출력

3. 스코프 연산자 붙여서 뽑으니까 전역변수에 50 더해져서 150나옴

 

== 스코프 연산자 붙으면 전역변수임

 

 

String

#include <iostream>

using namespace std;

int main() {
	char ch1 = 'A';
	char ch2[10] = "홍길동\0";

	cout << ch1 << endl;
	cout << ch2 << endl;

	string country = "Korea";
	string city = "Busan";

	cout << country << endl;
	cout << city << endl;

	string my_info = "I live in " + country + ", " + city;
	cout << "My information: " << my_info << endl;

	return 0;

}

728x90