반응형

6.5> 동일한 크기로 배열을 변환하는 다음 2개의 static 멤버 함수를 가진 ArrayUtility 클래스를 만들어라.

<코드>

#include <iostream>

 

using namespace std;

 

class ArrayUtility{

public:

        static void intToDouble(int source[], double dest[], int size);

        //int[] double[] 변환

        static void doubleToInt(double source[], int dest[], int size);

        //double[] int[] 변환

};

void ArrayUtility::intToDouble(int source[], double dest[], int size){

        for(int i=0;i<size;i++){

               dest[i]=(double)source[i]; //강제 형변환

        }

}

void ArrayUtility::doubleToInt(double source[], int dest[], int size){

        for(int i=0;i<size;i++){

               dest[i]=(int)source[i]; //강제 형변환, 소수점은 날아간다.

        }

}

int main(void){

        int x[]={1,2,3,4,5};

        double y[5];

        double z[]={9.9,8.8,7.7,6.6,5.6};

 

        ArrayUtility::intToDouble(x,y,5); // x[]-> y[]

        for(int i=0;i<5;i++) cout << y[i] << ' ';

        cout << endl;

        ArrayUtility::doubleToInt(z,x,5); //z[]->x[]

        for(int i=0;i<5;i++) cout << x[i] << ' ';

        cout << endl;

        return 0;

}


<결과창>



}


반응형

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

Random 클래스  (0) 2017.12.25
배열 빼기  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
반응형

6.4> 다음 클래스에 중복된 생성자를 디폴트 매개 변수를 가진 하나의 생성자로 작성하고 테스트 프로그램을 작성하라.

<코드>

#include <iostream>

 

using namespace std;

 

class MyVector{

private:

        int* mem;

        int size;

public:

        MyVector(int n,int val);

        ~MyVector(){delete []mem;} //동적 배열이 할당받은 메모리를 힙에 반환

        void printVector();

};

 

MyVector::MyVector(int n=100,int val=0){

        //n실인자가 입력되지 않으면 100대입,val 실인자 없으면 0대입

        mem=new int[n]; //n크기의 인트형 동적 배열

        size=n;

        for(int i=0;i<size;i++)

               mem[i]=val; //동적 배열의 모든 원소를 val 초기화해준다.

}

void MyVector::printVector(){ //10개씩 끊어서 출력

        int moc=size/10; //

        int namuji=size%10; //나머지

        for(int j=0;j<moc;j++){

        for(int i=0;i<10;i++){cout<<mem[i];} //몫에 해당하는만큼 출력

        cout<<endl;

        }

        for(int k=0;k<namuji;k++) //나머지에 해당하는 만큼 출력

               {cout<<mem[k];}

        cout<<endl;

}

int main(void){

        MyVector m1; //사이즈 100, 원소는 0

        MyVector m2(53); //사이즈 53, 원소는 0

        MyVector m3(27,3); //사이즈 27, 원소는 3

        m1.printVector();

        m2.printVector();

        m3.printVector();

        return 0;

}

<결과창>

                              

 

반응형

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

배열 빼기  (0) 2017.12.25
동일한 크기의 배열  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
반응형

6.2> Person 클래스의 객체를 생성하는 main() 함수는 다음과 같다.

(1) 생성자를 중복 작성하고 프로그램을 완성하라.

<코드1>

#include <iostream>

#include <string>

 

using namespace std;

 

class Person{

private:

        int id;

        double weight;

        string name;

public:

        void show(){cout<<id<<" "<<weight<<" "<<name<<endl;} //출력함수

        Person();

        Person(int id, string name);

        Person(int id,string name,double weight); //생성자 오버로딩

};

Person::Person(){//매개변수 없는 생성자

        this->id=1;

        this->weight=20.5;

        this->name="Grace";

}

Person::Person(int id, string name){ //매개변수 2개인 생성자

        this->id=id;

        this->weight=20.5;

        this->name=name;

}

 

Person::Person(int id,string name,double weight){ //매개변수 3개인 생성자

        this->id=id;

        this->name=name;

        this->weight=weight;

}

 

int main(void){

        Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);

        grace.show();

        ashley.show();

        helen.show();

        return 0;

}

 

 

(2) 디폴트 매개 변수를 가진 하나의 생성자를 작성하고 프로그램을 완성하라.

<코드2>

#include <iostream>

#include <string>

 

using namespace std;

 

class Person{

private:

        int id;

        double weight;

        string name;

public:

        void show(){cout<<id<<" "<<weight<<" "<<name<<endl;} //출력함수

        Person(int id,string name,double weight);

};

Person::Person(int id=1,string name="Grace",double weight=20.5){ //디폴트매개변수를 가진 생성자

        this->id=id;

        this->name=name;

        this->weight=weight;

        //id 입력이 없으면 1 대입, name 입력이 없으면 "Grace" 대입, weight 입력이 없으면 20.5 대입

}

 

int main(void){

        Person grace, ashley(2, "Ashley"), helen(3, "Helen", 32.5);

        grace.show();

        ashley.show();

        helen.show();

        return 0;

}

 

 

<결과창>

   

    


반응형

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

동일한 크기의 배열  (0) 2017.12.25
생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
모스 부호  (0) 2017.11.09
반응형


인하대학교 전자공학과 전자회로실험2 결과보고서 Atmega 개발 환경 & GPIO


인하대학교 전자공학과 전자회로실험2 결과보고서 USART 통신


인하대학교 전자공학과 전자회로실험2 결과보고서 LCD


인하대학교 전자공학과 전자회로실험2 결과보고서 timer counter


인하대학교 전자공학과 전자회로실험2 결과보고서 interrupt


인하대학교 전자공학과 전자회로실험2 결과보고서 ADC


문의는 댓글이나 방명록에 써주시면 됩니다.

반응형
반응형
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
#include <iostream>
 
using namespace std;
 
class A {
public:
     virtual void print() { cout << "에이" << endl; }
};
class B : public A {
public:
 virtual void print() { cout << "비" << endl; }
};
 
class C : public B {
public:
    virtual void print() { cout << "씨" << endl; }
};
 
/*참고로, 부모 클래스에서 멤버 함수 선언문 앞에 virtual 키워드가 존재한다면,
자식 클래스에서 오버라이딩(재정의, Overriding)한 함수도 저절로 가상 함수로 정의됩니다.
그러나, 소스 코드의 이해를 돕기 위해 자식 클래스에도 virtual를 명시해주어야 하는것이 관례입니다.
이번엔 순수 가상 함수(Pure Virtual Function)란 녀석을 살펴보도록 하겠습니다.
출처: http://blog.eairship.kr/175 [누구나가 다 이해할 수 있는 프로그래밍 첫걸음]*/
 
int main(void) {
 
    A* p;
    A* a = new A();
    a->print(); //a->A
    B* b = new B();
    b->print(); //b->B
    C* c = new C();
    c->print(); //c->C
    c =(C*) b;  
    c->print(); //c->B
    c = (C*)a;
    c->print(); //c->A
    p = a;
    p->print(); //(p=a)->A
    p = b;
    p->print(); //(p=b)->B
    p = c; 
    p->print(); //(p=c)->A
    
 
}
cs



virtual 을 쓰면 중요한 것은 원래 객체가 어떤 타입이냐!!이다.


반응형

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

생성자 오버로딩의 디폴트 매개변수로의 변환  (0) 2017.12.25
생성자 중복 디폴트 매개 변수  (0) 2017.12.25
operator overloading  (0) 2017.11.14
모스 부호  (0) 2017.11.09
Book 클래스  (1) 2017.11.09
반응형
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
#include <iostream>
using namespace std;
 
class Power{
    int kick;
    int punch;
public:
    Power(int kick=0int punch=0){
        this->kick=kick; this->punch=punch;
    }
    void show();
    friend Power operator+(int op1, Power op2); //정수+객체를 위하여..
    Power operator+(int op2); //객체+정수를 위하여..
};
void Power::show(){
    cout<<"kick="<<kick<<","<<"punch="<<punch<<endl;
}
Power operator+(int op1,Power op2){
    Power tmp;
    tmp.kick=op1+op2.kick;
    tmp.punch=op1+op2.punch;
    return tmp;
}
Power Power::operator+(int op2){
    Power tmp;
    tmp.kick=this->kick + op2;
    tmp.punch=this->punch +op2;
    return tmp;
}
 
int main(void){
    Power a(3,5), b,c;
    a.show();
    b.show();
    c.show();
    b=2+a;
    c=a+3;
    a.show();
    b.show();
    c.show();
}
cs




연산자 오버로딩을 클래스의 멤버 함수로 정의하는 방법과 외부 함수로 정의한 후 프렌드 선언을 해주는 방법이 있는데

operand(피연산자) 순서의 차이를 보인다. 만약 둘 중 한가지 방법만 쓴다면

프로그램 작성시 operand의 순서를 조심해야겠다.

반응형

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

생성자 중복 디폴트 매개 변수  (0) 2017.12.25
virtual 함수  (0) 2017.11.23
모스 부호  (0) 2017.11.09
Book 클래스  (1) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
반응형

Open Challenge> 아래< 5-1>을 참고하여 영문 텍스트, 숫자, 몇 개의 특수 문자로 구성되는 텍스트를 모스 부호로 변환하는 프로그램을 작성하라. 모스 부호는 전보를 쳐서 통신하는 시절에 사용된 유명한 코딩 시스템이다. 각 모스 코드들은 하나의 빈칸으로 분리되고, 영문 한 워드가 모스 워드로 변환되면 워드들은 3개의 빈칸으로 분리된다. 실행 예는 다음과 같다. 영문 텍스트를 입력받아 모스 부호로 변환하여 출력하고, 변환이 잘 되었는지 확인하기 위해 다시 모스 부호를 영문 텍스트로 변환하여 원문을 출력한 사례이다.


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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <algorithm>
#include <string>
 
using namespace std;
 
class Morse{
private:
    string alphabet[26]; //알파벳의 모스 부호 저장
    string digit[10]; //숫자의 모스 부호 저장
    string slash, question, comma, period, plus, equal; //특수 문자의 모스 부호 저장
public:
    Morse(); //alphabet[], digit[] 배열 및 특수 문자의 모스 부호 초기화
    void text2Morse(string text, string& morse); //영문 텍스트를 모스 부호로 변환
    bool morse2Text(string morse, string& text); //모스 부호를 영문텍스트로 변환
};
Morse::Morse(){
    string Malphabet[26]=".-""-...""-.-.""-.."".","..-.""--.""...."".."".---",
                   "-.-"".-..""--""-.""---",".--.""--.-"".-.""...""-",
                   "..-""...-"".--""-..-""-.--""--.."};
    string Mdigit[10]={"-----"".----""..---""...--""....-"".....""-....""--...""---..""----." };
    slash= "-..-.";    question= "..--..";    comma= "--..--";
    period= ".-.-.-";  plus= ".-.-.";     equal= "-...-"//모스 특수문자 초기화
    int i;
    for(i=0;i<26;i++){alphabet[i]=Malphabet[i];} //모스 알파벳 초기화
    for(i=0;i<10;i++){digit[i]=Mdigit[i];} //모스 숫자 초기화
}
void Morse::text2Morse(string text, string& morse){
    transform(text.begin(),text.end(),text.begin(),tolower); // 입력한 문자열을 전부 소문자로 바꾼다.
    for(int i=0;i<text.length();i++){
        if(text[i]>=97&&text[i]<=122){morse=morse+alphabet[text[i]-97]+" ";} //해당 인덱스가 알파벳일 경우 해당 모스 부호 삽입
        else if(text[i]==' '){morse+="   ";} //해당 인덱스가 공백문자 일경우 공백문자 3개 입력
        else if(text[i]>=48&&text[i]<=57){morse=morse+digit[text[i]-48]+" ";} //해당 인덱스가 숫자 일경우 해당 모스 부호 삽입
        else if(text[i]=='/'){morse=morse+slash+" ";}
        else if(text[i]=='?'){morse=morse+question+" ";}
        else if(text[i]==','){morse=morse+comma+" ";}
        else if(text[i]=='.'){morse=morse+period+" ";}
        else if(text[i]=='+'){morse=morse+plus+" ";}
        else if(text[i]=='='){morse=morse+equal+" ";} //해당 인덱스가 특수문자 일경우 해당 모스 부호 삽입
    }
}
bool Morse::morse2Text(string morse, string& text){
    string regen; //다시 읽을 수 있게 복원한 것을 넣을 스트링
    string sub; // 공백 문자 단위로 자름
    int i;
    int startindex=0//문자를 찾기 시작할 첫번째 index
    int blankindex=-1//공백문자의 index
    int swch=1//모스부호가 무엇인지 검사하는데 사용할 플래그
    while(1){
        swch=1//플래그는 루프 돌때마다 1로 ON
        startindex=blankindex+1//찾기 시작할 인덱스는 공백 인덱스 더하기 1
        blankindex=morse.find(" ",blankindex+1); //전에 찾았던 것을 또 찾으면 안되니 더하기 1을해서 공백문자를 찾는다.
        sub=morse.substr(startindex,blankindex-startindex); // 공백 문자를 제외한 무언가를 나타내는 모스부호 부분만 자른다.
        for(i=0;i<26;i++){
            if(alphabet[i]==sub)
                {regen+=(char)(97+i);
            swch=0;break;}    //알파벳일 경우 변환하여 regen에 더하고 플래그 OFF 후 루프 탈출
        }
        if(swch==1){
            for(i=0;i<10;i++){
                if(digit[i]==sub)
                {regen+=(char)(48+i);
                swch=0;break;}
            } //숫자일 경우 변환하여 regen에 더하고 플래그 OFF 후 루프 탈출
        }
        if(swch==1){
            if(sub==slash){regen+="/";}
            else if(sub==question){regen+="?";}
            else if(sub==comma){regen+=",";}
            else if(sub==period){regen+=".";}
            else if(sub==plus){regen+="+";}
            else if(sub==equal){regen+="=";}
        } //특수문자일 경우 regen에 더한다. 
 
        if(blankindex==morse.length()-1){break;} //여기서 검사하는 이유는 인덱스가 맨 마지막일때 +1,+2,+3 을 검사하면 오류가 나기 때문이다.
        if((morse[blankindex+1]==' ')&&(morse[blankindex+2]==' ')&&(morse[blankindex+3]==' ')){
            regen+=" ";     cout<<regen<<endl//제대로 이어졌나 확인.
            blankindex+=3//공백문자가 연달아 3개 있으면 실제에서는 공백문자 하나를 뜻한다. 이를 검사하기 위함.
        }
        }
    if(regen==text) return true//새로 만든 문자열과 원래 문자열이 같으면 true리턴
    else return false//아니면 false 리턴
}
int main(void){
    Morse m;
    string english;
    string morse;
    cout<<"아래에 영문 텍스트를 입력하세요. 모스 부호로 바꿉니다."<<endl;
    getline(cin,english,'\n'); //개행문자 나올 때까지 문자열 받는다
    m.text2Morse(english,morse); //모스부호로 전환
    cout<<morse<<endl;
    cout<<"모스 부호를 다시 영문 텍스트로 바꿉니다."<<endl;
    if(m.morse2Text(morse,english)) //다시 읽을 수 있는 텍스트로 전환
        cout<<english<<endl//만약 같으면 원래 문자열 출력
    else
        cout<<"오류 발생"<<endl//다르면 오류발생 출력
    return 0;
}
 
cs




반응형

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

virtual 함수  (0) 2017.11.23
operator overloading  (0) 2017.11.14
Book 클래스  (1) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
반응형

5.8> 책의 이름과 가격을 저장하는 다음 Book 클래스에 대해 물음에 답하여라.

(1) Book 클래스의 생성자, 소멸자, set() 함수를 구현하라.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Book::Book(char* title, int price){ // 타이틀과 가격 초기화
    (this->title)=new char[strlen(title)+1]; //사이즈만큼 동적메모리 할당
    strcpy(this->title,title); //strcpy로 복사
    this->price=price; //price 대입
}
Book::~Book(){
    if(title) //title이 NULL이아니면
        delete []title; //동적메모리 반환
}
void Book::set(char* title, int price){
    if(strlen(this->title)<=strlen(title)) //새로대입하는 문자열의 길이가 기존보다 길면
        {
        delete []title;  //동적메모리반환후
        (this->title)=new char[strlen(title)+1];} //새로 그 길이만큼 동적메모리 받아온다.
    
    strcpy(this->title,title); //strcpy로 복사
    this->price=price;
}
 
cs


(2) 컴파일러가 삽입하는 디폴트 복사 생성자 코드는 무엇인가?


1
2
3
4
5
Book::Book(Book& book){
        this->title=book.title;
        this->price=book.price;
    }
 
cs


(3) 디폴트 복사 생성자만 있을 때 아래 main() 함수는 실행 오류가 발생한다. 다음과 같이 실행 오류가 발생하지 않도록 깊은 복사 생성자를 작성하라.


1
2
3
4
5
6
Book::Book(Book& book){
    (this->title)=new char[strlen(book.title)+1];
    strcpy(this->title,book.title);
    this->price=book.price;
}
 
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <cstring>
 
using namespace std;
 
class Book{
private:
    char *title; //제목 문자열
    int price; //가격
public:
    Book(char* title, int price);
    Book(Book& book);
    ~Book();
    void set(char* title, int price);
    void show(){cout<<title<<' '<<price<<"원"<<endl;}
    
};
Book::Book(char* title, int price){ // 타이틀과 가격 초기화
    (this->title)=new char[strlen(title)+1]; //사이즈만큼 동적메모리 할당
    strcpy(this->title,title); //strcpy로 복사
    this->price=price; //price 대입
}
Book::Book(Book& book){
    (this->title)=new char[strlen(book.title)+1];
    strcpy(this->title,book.title);
    this->price=book.price;
}
Book::~Book(){
    if(title) //title이 NULL이아니면
        delete []title; //동적메모리 반환
}
void Book::set(char* title, int price){
    if(strlen(this->title)<=strlen(title)) //새로대입하는 문자열의 길이가 기존보다 길면
        {
        delete []title;  //동적메모리반환후
        (this->title)=new char[strlen(title)+1];} //새로 그 길이만큼 동적메모리 받아온다.
    
    strcpy(this->title,title); //strcpy로 복사
    this->price=price;
}
 
 
int main(void){
    Book cpp("명품C++"10000); //초기화
    Book java=cpp; //깊은복사
    cpp.show(); 
    java.show();
    return 0;
}
 
cs




반응형

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

operator overloading  (0) 2017.11.14
모스 부호  (0) 2017.11.09
Accumulator 클래스  (0) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
반응형

5.7> 클래스 Accumulator add() 함수를 통해 계속 값을 누적하는 클래스로서, 다음과 같이 선언된다. Accumulator 클래스를 구현하라.


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
#include <iostream>
 
using namespace std;
 
class Accumulator{
private:
    int value;
public:
    Accumulator(int value);//매개 변수 value 로 멤버 value 초기화
    Accumulator& add(int n); //vlaue에 n을 더해 값 누적
    int get(); //누적된 값 value 리턴
};
Accumulator::Accumulator(int value){
    this->value=value; //value 값 이니셜라이징
}
Accumulator& Accumulator::add(int n){
    value+=n;
    return *this//리턴타입이 참조이다. this는 포인터이므로 역참조 연산자를 통해
                //참조를 리턴할 수 있다.
}
int Accumulator::get(){
    return value; //총더해진 값을 리턴
}
 
int main(void){
    Accumulator acc(10); //초기값 10
    acc.add(5).add(6).add(7); //5,6,7을 차례로 더한다
    cout<<acc.get(); //최종 더해진 값 리턴 (즉 28)
    return 0;
}
 
cs




반응형

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

모스 부호  (0) 2017.11.09
Book 클래스  (1) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
반응형

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
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
 
using namespace std;
 
int main(void){
 
    char c=3;
    int a=1;
    double d=1.0;
 
    char *p1=&c;
    int *p2=&a;
    double *p3=&d;
    cout<<"캐릭터 "<<(int)p1<<" "<<(int)(p1+1)<<endl//1->주소1증가
    cout<<"정수 "<<(int)p2<<" "<<(int)(p2+1)<<endl//1->주소4증가
    cout<<"실수(더블) "<<(int)p3<<" "<<(int)(p3+1)<<endl;//1->주소8증가
}
cs




char 포인터에 더하기 1을 하면 주소는 1이 증가
int 포인터에 더하기 1을 하면 주소는 4이 증가
double 포인터에 더하기 1을 하면 주소는 8이 증가
헷갈리지 말자




반응형

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

Accumulator 클래스  (0) 2017.11.09
MyIntStack 클래스  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
using namespace std;
 
int main(void){
 
    int a[2]={6,10};
    int *p=a; //포인터 p는 배열a의 첫번째 원소를 가리키는 포인터
    int &r=*a; //r은 a의 첫번째 원소의 참조
    int &r2=r; //r2는 r의 참조 (참조의 참조)
 
    cout<<a[0]<<endl//6
    cout<<*p<<endl//6
    cout<<r<<endl//6
    cout<<r+1<<endl//6+1=7
    cout<<a<<endl//주소
    cout<<&r<<endl//첫번째 원소의 주소 =a
    cout<<*(&r)<<endl//레퍼런스 주소의 역참조 = 6
    cout<<*(&r+1)<<endl//레퍼런스 주소에 1을 더한것의 역참조 = 10(2번째 원소)
    cout<<r2<<endl//r2는 r을 가리키므로 6
}
cs


포인터는 주소가 담기는 메모리가 할당 된다.

레퍼런스는 메모리 상의 특정 공간을 차지하는 것이 아니라 컴파일 시에

원래 레퍼런스가 참조하던 변수의 *(주소값)으로 대체되는 것이다.







반응형

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

MyIntStack 클래스  (0) 2017.11.09
포인터의 증감  (0) 2017.11.09
float와 double  (0) 2017.11.05
히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
using namespace std;
 
float dorf(float a){return 123;}
double dorf(double a){return 456;}
 
int main(void){
    cout<<dorf(3.0)<<endl;
    cout<<dorf((float)3.0)<<endl;
    cout<<dorf((double)3.0)<<endl;
 
    return 0;
}
cs


함수의 리턴 타입을 float, double로 오버로딩하면

강제 형변환을 하지 않고 실수를 넣었을 때

기본적으로 double이 나온다.

안에 들어간 실수 인자를 double로 자동인식하는 것 같다.




반응형

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

포인터의 증감  (0) 2017.11.09
변수와 포인터와 참조  (0) 2017.11.08
히스토그램  (0) 2017.11.03
Circle, CircleManager 클래스  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
반응형

4.10> 영문자로 구성된 텍스트에 대해 각 알파벳에 해당하는 문자가 몇 개인지 출력하는 히스토그램 클래스 Histogram을 만들어보자. 대문자는 모두 소문자로 변환하여 처리한다. Histogram 클래스를 활용하는 사례와 실행 결과는 다음과 같다.


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
#include <iostream>
#include <algorithm> //transform 함수 사용 위함
#include <string>
 
using namespace std;
 
class Histogram{
private:
    string s; //스트링 저장용
public:
    Histogram(string s){(this->s)+=s;} //생성자는 멤버스트링 s에 매개스트링 s를 더한다.
    void put(string s){(this->s)+=s;} //멤버스트링 s에 매개스트링 s를 더한다.
    void putc(char c){(this->s)=s+c;} //멤버스트링 s에 매개 캐릭터 c를 더한다.
    void print(){
        cout<<s<<endl//소문자화 하기전 출력
        transform(s.begin(),s.end(),s.begin(),tolower); //스트링 s를 전부 소문자화 시킴
        cout<<s<<endl//소문자화 한 후 출력
        for(int i=0;i<26;i++){ //알파벳이 26자라서 26번 돌린다.
            int count=0//알파벳 몇번 나왔나 셀 때 사용할 변수
            for(int k=0;k<s.size();k++){ //스트링 전부 순회
                if(s[k]==(i+97)) //아스키코드 97이 'a'라서 97~97+26 은 'a'~'z'를 의미한다. s의 각 문자를 'a'~'z'와 비교
                    count++//만약 s[k]가 i+97과 같으면 count 증가
            }
            cout<<(char)(i+97)<<" ("<<count<<")    :    "//출력
 
            for(int j=0;j<count;j++//count 수만큼 별 출력
                {cout<<"*";}
            cout<<endl//한줄 내린다.
        }
    }
};
 
int main(void){
    Histogram elvisHisto("Wise men say, only fools rush in But I can't help, ");
    elvisHisto.put("falling in love with you");
    elvisHisto.putc('-');
    elvisHisto.put("Elvis Presley");
    elvisHisto.print();
    return 0;
}
 
cs




반응형

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

변수와 포인터와 참조  (0) 2017.11.08
float와 double  (0) 2017.11.05
Circle, CircleManager 클래스  (0) 2017.11.03
Person, Family 클래스  (0) 2017.11.03
원의 개수와 반지름  (0) 2017.11.03
반응형

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
반응형

4.6> 실습 문제 5의 문제를 수정해보자. 사용자로부터 다음과 같이 원의 개수를 입력받고, 원의 개수만큼 반지름을 입력받는 방식으로 수정하라. 원의 개수에 따라 동적으로 배열을 할당받아야 한다.


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
#include <iostream>
 
using namespace std;
 
class Circle{ //Circle 클래스
private:
    int radius; //private 타입 인티저 radius
public:
    void setRadius(int radius);
    double getArea();
};
void Circle::setRadius(int radius){  //radius 셋하는 함수
    this->radius=radius; //this->radius는 클래스의 멤버 변수,radius는 멤버 함수의 매개 변수
}
double Circle::getArea(){ //넓이를 구해주는 멤버 함수 getArea
    return radius*radius*3.14;
}
 
int main(void){
    int n=0// 원의 개수
    int count=0//면적이 100보다 큰 원 개수
    int r; //반지름을 담을 변수
    while(true){ //원의 개수를 1보다 작게 했을 때 생기는 오류를 없애주는 무한루프
    cout<<"원의 개수 >> ";
    cin>>n; //n을 받는다.
        if(n>=1//n이 1보다 크면 무한루프 탈출
            break;
    }
    Circle *p=new Circle[n]; //Circle 객체를 동적으로 n개 생성 해당포인터 p
    for(int i=0;i<n;i++){
        cout<<"원 "<<i+1<<"의 반지름 >> "
        cin>>r;
        p[i].setRadius(r); //p[i]의 radius를 r로 설정해준다
        if(p[i].getArea()>100//p[i]의 넓이가 100보다크면
            count++//카운트를 늘려준다.
    }
    cout<<"면적이 100보다 큰 원은 "<<count<<"개 입니다."<<endl//100보다큰원 출력
    delete []p; //동적 배열 메모리 힙에 반환
}
 
cs




반응형
반응형

4.3> string 클래스를 이용하여 사용자가 입력한 영문 한 줄을 입력받고 글자 하나만 랜덤하게 수정하여 출력하는 프로그램을 작성하라.


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 <cstdlib> //random 사용 위함
#include <ctime> //srand 사용 위함
#include <string> //string 객체 사용 위함
 
using namespace std;
 
int main(void){
    string s; //string 객체 s
    srand((unsigned)time(0)); //시드값 설정
    
    cout<<"아래에 한 줄을 입력하세요.(exit를 입력하면 종료합니다)"<<'\n';
    while(true){ //무한루프
    cout<<">>";
    getline(cin,s,'\n'); //delimeter '\n'으로 한 줄 받아 s에 저장
    if(s=="exit"//s가 exit면 루프 탈출
        break;
    int rand_index=(rand())%(s.length()); //rand_index에 임의 인덱스 저장(s.length로 나눈 나머지는 무조건 0~length-1이 나옴)
    //조심해야 할것은 알파벳만 인덱스에 포함되는 것이 아니라 공백문자, 마침표와 같은 문자도 포함된다.
    int Daeso=rand()%2//글자를 바꾸는데 소문자로 바꿀 것인지 대문자로 바꿀 것인지 랜덤으로 정한다.
    if(Daeso==0//대문자로 정해짐
    s[rand_index]=(char)((rand()%26)+65); //아스키코드 65~90 대문자 알파벳
    else if(Daeso==1//소문자로 정해짐
    s[rand_index]=(char)((rand()%26)+97); //아스키코드 97~122 소문자 알파벳
    cout<<s<<endl//s출력
    }
    return 0;
}
 
cs



반응형
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
 
using namespace std;
 
int main(void){
    int a;
    int &b=a;
    int *c=&a;
    a=7;
    cout<<"a="<<a<<" b="<<b<<" *c="<<*c<<endl;
    cout<<"&a="<<&a<<" &b="<<&b<<" c="<<c<<endl;
 
    return 0;
}
cs






a는 int형 변수
b는 a의 별명(레퍼런스, 참조)
c는 a를 가리키는 포인터 변수
즉 a와 b와 *c는 같을 것이고
&a 와 &b와 c는 같을 것이다.
헷갈리지 말자~!


반응형
반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
 
using namespace std;
 
namespace yh{
    class test{
    public:
        int test_print();
    };
}
 
int yh::test::test_print(){
    return 3;
}
 
int main(void){
    
    yh::test c;
    cout<<c.test_print()<<endl;
    
    return 0;
}
cs


리턴타입 네임스페이스명::클래스명::함수명(arguments){}


과 같이 해주면 된다.  자바의 솔루션과 비슷한 개념 같은데 디렉토리가 따로 생성되지는 않는 것을 보아


좀 더 저급한 개념인 것 같다. 이것이 발전해서 자바의 패키지가 된 것 같다. (나의 생각)

반응형

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

문자열 문자 랜덤 수정  (0) 2017.11.03
변수와 포인터와 레퍼런스  (0) 2017.10.27
다수의 클래스 연산자  (0) 2017.10.12
Integer 클래스  (0) 2017.10.12
SelectableRandom 클래스  (0) 2017.10.12

+ Recent posts