💻 프로그래밍 언어/C++
C++ 14주차
SA성아
2023. 12. 6. 12:36
static
실습 9-1: 동적바인딩(지역 변수)과 정적바인딩(static변수)
#include <iostream>
using std::cout;
void sub();
int main()
{
cout << "start\n";
sub();
sub();
sub();
return 0;
}
void sub()
{
int x = 10;
//동적 바인딩, run-time시
int y = 10;
//정적 바인딩, y의 초기값은 컴파일시 10으로
//정해지며 실행시에 이 선언문은 실행하지 않음
cout << x << y << '\n';
x++;
y++;
}
#include <iostream>
using std::cout;
void sub();
int main()
{
cout << "start\n";
sub();
sub();
sub();
return 0;
}
void sub()
{
int x = 10;
//동적 바인딩, run-time시
static int y = 10;
//정적 바인딩, y의 초기값은 컴파일시 10으로
//정해지며 실행시에 이 선언문은 실행하지 않음
cout << x << y << '\n';
x++;
y++;
}
[정적 바인딩, early binding]
▶ 컴파일할 때 y값이 결정이된다.
▶ 선언문은 실행하지 않는다.
[동적 바인딩, late binding]
▶ 실행 시(run-time) 변수의 위치와 함수가 실행할 명령이 결정
실습 9-2: 정적(static) 멤버변수
#include <iostream>
using std::cout;
class Point {
int x;
int y;
int count; //선언
public:
Point() { cout << ++count; }
~Point() { cout << --count; }
};
//int Point::count = 0; //정의
int main()
{
Point p1, p2, p3;
return 0;
}
#include <iostream>
using std::cout;
class Point {
int x;
int y;
static int count; //선언
public:
Point() { cout << ++count; }
~Point() { cout << --count; }
};
int Point::count = 0; //정의
int main()
{
Point p1, p2, p3;
return 0;
}
▶ 모든 객체가 공유하는 멤버변수
▶ 한 클래스로부터 객체가 여러 개 만들어지더라도 이 멤버변수는 하나만 생성됨
▶ 여러 객체들에서 공유해야 하는 정보는 정적 멤버변수로 선언
▶ 선언만 하면 안되고 정의도 해야 한다.
▶ 모든 객체가 공유하고 싶은 자료가 있으면, 변수 앞에 static을 쓰면 된다.
템플릿(template)
STL(Standard Template Library)
예외처리
Generic: 자료형이 나중에 결정되는 것
함수 중첩으로 만족하지 말자!
함수 중첩(overloading)
#include <iostream>
using std::cout;
using std::endl;
int Max(int i, int j)
{
return i > j ? i : j;
}
double Max(double i, double j)
{
return i > j ? i : j;
}
char Max(char i, char j)
{
return i > j ? i : j;
}
int main()
{
cout << "Max값은=" << Max(1, 2) << endl;
cout << "Max값은=" << Max(7.5, 3.6) << endl;
cout << "Max값은=" << Max('A', 'B');
return 0;
}
템플릿(template)
#include <iostream>
using std::cout;
using std::endl;
template <class T>
//template <typename T> class랑 똑같다
T Max(T i, T j)
{
return i > j ? i : j;
}
int main()
{
cout << "Max값은=" << Max(1, 2) << endl;
cout << "Max값은=" << Max(7.5, 3.6) << endl;
cout << "Max값은=" << Max('A', 'B');
return 0;
}
이 소스를 템플릿을 이용하여 일반화된 클래스로 구현
#include <iostream>
using std::cout;
using std::endl;
class CCC1
{
int x;
int y;
public:
CCC1(int xx, int yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
class CCC2
{
double x;
double y;
public:
CCC2(double xx, double yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
class CCC3
{
char x;
char y;
public:
CCC3(char xx, char yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
int main()
{
CCC1 c1(10, 20);
CCC2 c2(3.5, 5.5);
CCC3 c3('I', "Love You!");
c1.Print();
c2.Print();
c3.Print();
return 0;
}
#include <iostream>
using std::cout;
using std::endl;
template <typename T>
class CCC1
{
T x;
T y;
public:
CCC1(T xx, T yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
int main()
{
CCC1<int> c1(10, 20);
CCC1<double> c2(3.5, 5.5);
CCC1<char> c3('I', 'U');
c1.Print();
c2.Print();
c3.Print();
return 0;
} //작년 10점 문제
▶ < 자료형을 나중에 결정하는 방식 >
#include <iostream>
using std::cout;
using std::endl;
class CCC1
{
int x;
int y;
public:
CCC1(int xx, int yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
class CCC2
{
double x;
double y;
public:
CCC2(double xx, double yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
class CCC3
{
char x;
const char* y;
public:
CCC3(char xx, const char* yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
int main()
{
CCC1 c1(10, 20);
CCC2 c2(3.5, 5.5);
CCC3 c3('I', "Love You!");
c1.Print();
c2.Print();
c3.Print();
return 0;
}
#include <iostream>
using std::cout;
using std::endl;
template <class T1, class T2>
class CCC1
{
T1 x;
T2 y;
public:
CCC1(T1 xx, T2 yy) { x = xx; y = yy; }
void Print() { cout << x << ',' << y << endl; }
};
int main()
{
CCC1<int, int> c1(10, 20);
CCC1<double, double> c2(3.5, 5.5);
CCC1<char, const char*> c3('I', "Love You!");
c1.Print();
c2.Print();
c3.Print();
return 0;
} //재작년 15점
vector 컨테이너
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> x; //int x[10]와 차이
// 여러 개 int형을 가지고 노는 배열 공간을 만들고 싶어요
x.push_back(1);
x.push_back(2);
x.push_back(3);
for (int i = 0; i < x.size(); i++)
cout << x[i] << endl;
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> x;
x.push_back(1);
x.push_back(2);
x.push_back(3);
for (int i = 0; i < x.size(); i++)
cout << x[i] << endl;
vector <double> y;
y.push_back(1.2);
y.push_back(2.3);
y.push_back(3.1);
for (int i = 0; i < y.size(); i++)
cout << y[i] << endl;
return 0;
}
//typedef basic_string<char> string;
//http://www.cplusplus.com/reference/string/string/
//https://en.cppreference.com/w/cpp/string/basic_string
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "안녕!";
cout << str << endl;
str.push_back('H');
str.push_back('i');
str.push_back('a');
cout << str << endl; //안녕!Hi
for (int i = 0; i < str.size(); i++)
cout << str[i];
return 0;
}
vector container, iterator, algorithm, functor
#include <iostream>
#include <vector> // vector container
#include <algorithm> // sort
#include <functional> // 함수자 less<>, greater<>
using namespace std;
int main()
{
vector<int> v(5); //vector container
cout << v.size() << " : " << v.capacity() << endl; //5 :5
//capacity는 할당된 메모리 공간의 크기, size는 저장된 데이터 요소의 개수
for (int i = 0; i < v.size(); i++) cout << v[i] << ' '; //0 0 0 0 0
cout << endl;
for (int i = 0; i < v.size(); i++) v[i] = i + 1;
for (int i = 0; i < v.size(); i++) cout << v[i] << ' '; //1 2 3 4 5
cout << endl;
for (int i = 0; i < 5; i++) v.push_back(10 - i);
vector<int>::iterator iter; //iterator
for (iter = v.begin(); iter != v.end(); iter++)cout << *iter << ' ';
// 1 2 3 4 5 10 9 8 7 6
sort(v.begin(), v.end()); cout << endl; //algorithm
for (iter = v.begin(); iter != v.end(); iter++)cout << *iter << ' ';
// 1 2 3 4 5 6 7 8 9 10
sort(v.begin(), v.end(), greater<int>()); //functor
cout << endl;
for (iter = v.begin(); iter != v.end(); iter++)cout << *iter << ' ';
// 10 9 8 7 6 5 4 3 2 1
return 0;
}
예외처리(exception handling, error handling)
예외처리가 안 된 소스
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void Div(double ja, double mo)
{
cout << "결과:" << ja / mo << endl;
}
int main()
{
double x, y;
cout << "분자를 입력하세요=";
cin >> x;
cout << "분모를 입력하세요=";
cin >> y;
Div(x, y);
return 0;
}
예외처리 1단계: 예외가 발생할 수 있는 문장 try로 묶기
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void Div(double ja, double mo)
{
try {
cout << "결과:" << ja / mo << endl;
}
}
int main()
{
double x, y;
cout << "분자를 입력하세요=";
cin >> x;
cout << "분모를 입력하세요=";
cin >> y;
Div(x, y);
return 0;
}
2단계: 문제가 있는 값 던지기(throw)
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void Div(double ja, double mo)
{
try {
if (mo == 0) throw mo;
cout << "결과:" << ja / mo << endl;
}
}
int main()
{
double x, y;
cout << "분자를 입력하세요=";
cin >> x;
cout << "분모를 입력하세요=";
cin >> y;
Div(x, y);
return 0;
}
3단계: 예외가 발생했을 때 실행할 문장을 catch안에 넣는다
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
void Div(double ja, double mo)
{
try {
if (mo == 0) throw mo;
cout << "결과:" << ja / mo << endl;
}
catch(double){
cout << "오류: 0으로 나눌 수 없음";
}
}
int main()
{
double x, y;
cout << "분자를 입력하세요=";
cin >> x;
cout << "분모를 입력하세요=";
cin >> y;
Div(x, y);
return 0;
} //예전 시험문제
출처: c++ 프로그래밍 강의 자료