본문 바로가기

C++

C++ 8일차

C++ 8일차


생성자의 다양한 사용 방법


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
32
33
34
35
36
37
38
#include <iostream>
#include <cstdio>
 
using namespace std;
 
class comple{
public:
    comple() : real(0),img(0) {}
    comple(double a, double b) : real(a),img(b){}
    double GetReal() {
        return real;
    }
    void SetReal(double real_) {
        real = real_;
    }
    double GetImg() {
        return img;
    }
    void SetImg(double img_) {
        img = img_;
    }
    void print() {
        cout << "REAL : " << this->real << endl;
        cout << "img : " << this->img << endl;
    }
 
private:
    double real;
    double img;
};
 
int main() {
    comple a;
    comple b = comple(23);
    b.print();
    getchar();
    return 0;
}
cs


위의 예제는 생성자를 이용하여 초기화 시키는 방법중 하나 입니다.


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
#include <iostream>
#include <ctime>
#include <cstdio>
 
using namespace std;
 
class Time {
public:
    Time() : h(0), m(0), s(0){};
    Time(int s_) : s(s_) {};
    Time(int m_, int s_) : s(s_), m(m_) {};
    Time(int h_, int m_, int s_) : h(h_), m(m_), s(s_) {};
    void printt() {
        cout << "time : " << this-><< " " << this-><< " " << this-><< endl;
    }
private :
    int h;
    int m;
    int s;
};
 
int main(void) {
    int a, b, c;
    cin >> a >> b >> c;
    Time k = Time(a, b, c);
    k.printt();
    getchar();
    return 0;
}
cs


위의 예제는 생성자를 이용하여 초기화를 하고 캡슐화를 이용하여 자기가 원하는 시간을 입력하여 그 시간을 출력하는 예제입니다!!

'C++' 카테고리의 다른 글

C++ 10일차  (0) 2018.06.05
C++ 9일차  (0) 2018.06.02
C++7일차  (0) 2018.06.01
C++6일차  (0) 2018.06.01
C++5일차  (0) 2018.05.30