반응형

5.6> 문제 5번의 MyIntStack를 수정하여 다음과 같이 선언하였다. 스택에 저장할 수 있는 정수의 최대 개수는 생성자에서 주어지고 size 멤버에 유지한다. MyIntStack 클래스를 작성하라.


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
 
using namespace std;
 
class MyIntStack{
private:
    int *p; //스택 메모리로 사용할 포인터
    int size//스택의 최대 크기
    int tos; //스택의 탑을 가리키는 인덱스
public:
    MyIntStack();
    MyIntStack(int size);
    MyIntStack(MyIntStack& s);
    ~MyIntStack();
    bool push(int n); //정수 n을 스택에 푸쉬 꽉차있으면 false 아니면 true
    bool pop(int &n);  //스택의 탑에 있는 값을 n에 pop 한다 스택이 비었으면 false 아니면 true
};
MyIntStack::MyIntStack(){size=1;    p=new int[size];    tos=-1;} //기본 생성자 정의 tos=-1은 empty state를 나타낸다.
MyIntStack::MyIntStack(int size){this->size=size;    p=new int[size];    tos=-1;} //인자 size가 동적 배열의 크기를 결정한다.
//tos=-1이 empty 를 뜻하는 이유는 배열의 인덱스가 0부터 시작하기 때문이다.
MyIntStack::MyIntStack(MyIntStack& s){this->size=s.size
    p=new int[s.size]; //깊은 복사를 위해 새로운 동적메모리를 힙에서 size만큼 받아온다.
    for(int i=0;i<s.size;i++){
    (this->p)[i]=(s.p)[i];
    } //포인터에 할당된 동적메모리의 경우 깊은 복사를 위해
//새로운 할당을 해준 후 배열의 원소를 일일히 복사하여 넣어준다.
this->tos=s.tos;}
MyIntStack::~MyIntStack(){
    if(this->p) //p에 주소값이 NULL이 아니면
        delete []p; //p가 가리키는 동적메모리 반환
}
bool MyIntStack::push(int n){
    if((tos+1)==size//index는0부터 시작해서 1을 더해서 검사함
        return false;
    else{
        p[++tos]=n; //증가시키고 대입해준다.
        return true;
    }
}
bool MyIntStack::pop(int &n){
    if(tos==-1//empty면
        return false;
    else{
        n=p[tos--]; //대입하고 감소시킨다.
        return true;
    }
}
int main(void){
    MyIntStack a(10); //size 10짜리 마이인트스택 a
    a.push(10); //a에 10 삽입 pos=0
    a.push(20);//a에 20 삽입 pos=1
    MyIntStack b=a; //MyIntStack b(a); 와 같다.
    //객체로 초기화 하여 객체 생성,복사생성자 실행됨(깊은복사)
    b.push(30); //b에 30 삽입 pos=2
    int n;
    a.pop(n); //20 pop, pos=0이됨
    cout<<"스택 a에서 팝한 값 "<<n<<endl;
    b.pop(n); //30 pop, pos=1이됨
    cout<<"스택 b에서 팝한 값 "<<n<<endl;
    b.pop(n); //20 pop, pos=0이됨
    cout<<"스택 b에서 팝한 값 "<<n<<endl;
    b.pop(n); //10 pop, pos=-1이됨
    cout<<"스택 b에서 팝한 값 "<<n<<endl;
    cout<<b.pop(n)<<endl//pos=-1, empty state 라서 0 리턴
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

Book 클래스  (1) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
float와 double  (0) 2017.11.05
반응형

4.9> 다음은 이름과 반지름을 속성으로 가진 Circle 클래스와 이들을 배열로 관리하는 CircleManager 클래스이다. 키보드에서 원의 개수를 입력받고, 그 개수만큼 원의 이름과 반지름을 입력받고, 다음과 같이 실행되도록 main() 함수를 작성하라. Circle, CircleManager 클래스도 완성하라.


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>
 
using namespace std;
 
class Circle{ 
private:
    int radius;
    string name;
public:
    void setCircle(string name, int radius){ //멤버 name과 radius를 set해줌.
        this->name=name; this->radius=radius;
    }
    double getArea(){return radius*radius*3.14;} //원의 면적 리턴
    string getName(){return name;} //원의 이름 리턴
};
 
class CircleManager{
private:
    Circle *p; //Circle형 포인터 p
    int size;
public:
 
    CircleManager(int size){ //컨스트럭터
        this->size=size
        p=new Circle[size]; //size크기만큼의 Circle형 동적 객체 배열 생성
        int radius; string name;
        for(int i=0;i<size;i++){
            cin.ignore(100,'\n'); //cin은 개행문자를 버퍼에 남겨놓기 때문에 버퍼에서 비워줘야 한다.
                                //그렇지 않으면 다음 루프의 getline이 개행문자 + 입력한 문자열을 받아버린다.
            cout<<"원 "<<i+1<<"의 이름과 반지름 >>";
            getline(cin,name,' '); // space를 delimeter로 설정하여 이름을 받는다.
            cin>>radius;     //radius는 cin으로 받는다.
            p[i].setCircle(name,radius); //Circle을 set 해줌.
        }
    cin.ignore(); //마지막 개행문자 버퍼에서 제거
    }
    ~CircleManager(){delete []p;} //동적 Circle 객체 배열 해당 메모리 힙으로 반환
    void searchByName(){
        string cmp;
        cout<<"검색하고자 하는 원의 이름>> ";
        getline(cin,cmp,'\n'); //cmp를 getline으로 개행문자 나올때까지 받는다.
        for(int i=0;i<(this->size);i++){
            if(cmp==(p[i].getName()))  //cmp와 i번째 동적circle의 name이 같으면
            {cout<<"도넛의 면적은 "<<p[i].getArea()<<endl//i번째 동적circle의 area 반환
            break;}
        }
    }
    void searchByArea(){
        int area;
        cout<<"최소 면적을 정수로 입력하세요>> ";
        cin>>area; //area를 받는다.
        cout<<area<<"보다 큰 원을 검색합니다."<<endl;
        for(int i=0;i<(this->size);i++){ //동적 객체 배열 전부 순회하여 area보다 
            if(p[i].getArea()>area) //p번째 circle 객체의 넓이가 크면 출력
                cout<<p[i].getName()<<"의 면적은 "<<p[i].getArea()<<", ";
        }
        cout<<endl//개행 출력
    }
};
 
int main(void){
    int size;
    cout<<"원의 개수 >> " ; 
    cin>>size//원의 개수 정함
    CircleManager m(size); //CircleManager객체 생성
    m.searchByName(); //Name으로 찾기
    m.searchByArea(); //특정 Area 초과인것 찾기
    
    return 0;
}
 
cs




반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
반응형

4.8> 다음에서 Person은 사람을, Family는 가족을 추상화한 클래스로서 완성되지 않은 클래스이다. 다음 main()이 작동하도록 Person Family 클래스에 필요한 멤버들을 추가하고 코드를 완성하라.


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <string>
 
using namespace std;
 
class Person{ //Person 클래스
private:
    string name; 
public:
    Person(string name){this->name=name;} //객체멤버 name을 매개변수 name으로 초기화
    Person(){} //디폴트 생성자
    string getName(){return name;} // 멤버변수 name 리턴
    void setName(string name){this->name=name;} //멤버변수 name set함수
    
};
 
class Family{ //Family 클래스
private:
    Person *p; //Person형 포인터 p
    int size//int형 변수 size
    string Fname; //string 형 객체 Fname
public:
    Family(string name, int size){
        p=new Person[size]; //size 크기만큼 동적 Person 객체 배열 생성
        setFname(name); //Fname을 name으로 초기화
        this->size=size//멤버변수 size를 매개변수 size로 초기화
    }
    string getFname(){return Fname;} //Fname 리턴
    int getSize(){return size;} //size 리턴
    void setFname(string Fname){this->Fname=Fname;} //멤버변수 Fname을 매개변수 Fname으로 셋
    void setName(int num, string name){ 
        p[num].setName(name); //num에 해당하는 인덱스에 존재하는 동적 person 객체 배열 원소의 name 셋
    }
    void show(){
        cout<<getFname()<<"가족은 다음과 같이 "<<getSize()<<"명 입니다."<<endl//size 리턴받아 출력
        for(int i=0;i<size;i++){  //i가 0에서부터 size보다 작을때까지
            cout<<p[i].getName()<<"\t"//동적 person 객체 배열 원소에서 getName멤버 함수 호출하여 출력후 탭문자 출력
        }
        cout<<endl// 한줄 내리기
    }
    ~Family(){delete []p;} //소멸자는 동적person배열에 할당된 메모리를 힙에 반납한다. 
};
 
int main(void){
    Family *simpson = new Family("Simpson"3);  //Fname "Simpson", size 3으로 초기화된 Family형 동적 객체, 그걸 가리키는 포인터 simpson
    simpson->setName(0"Mr. Simpson"); //simpson이가리키는 객체 안에서원소3개의 person형 동적 객체 배열이 생성되었고 그중 0번 원소 초기화
    simpson->setName(1"Mrs. Simpson"); //1번 원소 초기화
    simpson->setName(2"Bart Simpson"); //2번 원소 초기화
    simpson->show(); //출력 함수
    delete simpson; //동적 메모리 힙으로 반환
}
 
cs



반응형

'컴퓨터 & 프로그래밍 & 전자공학 > C++' 카테고리의 다른 글

히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
문자열 문자 랜덤 수정  (0) 2017.11.03
변수와 포인터와 레퍼런스  (0) 2017.10.27

+ Recent posts