티스토리 뷰

190619(2일차) 생성자, 복사생성자, 소멸자
 
교육을 받으면서 노트필기 했던 내용을 날것 그대로 업로드합니다.
 

 
#include<iostream>
using namespace std;
#include"cstring"
 
 
 
 
class Car2 {
    int engine;
    int pipe;
    int piston;
 
public:
    Car2() : engine(10), pipe(10), piston(10) {}
    //Car2(int eg = 10 , int pp =10 , int pt=10) :engine(eg), pipe(pp), piston(pt) {}
    Car2() {}
    void print(void) {
        cout << engine << endl;
        cout << pipe << endl;
        cout << piston << endl;
 
    }
};
 
int main() {
    Car2 ob0; // 10, 10, 10
    Car2 ob1(200); //200 10, 10
    Car2 ob2(200, 30); //200 30, 10
    Car2 ob3(200, 30, 40); //200 30 40
    ob0.print();
    ob1.print();
    ob2.print();
    ob3.print();
 
}
 
 
 
 
 
class A {
private:
    int num;
    char* p;
public:
    A(int n, const char* ad) :num(n) { // 생성자
        num = n;
        p = new char[strlen(ad) + 1];
        strcpy(p, ad);
    }
    A(const A& cp) { // 복사 생성자
        num = cp.num;
        p = new char[strlen(cp.p) + 1];
        strcpy(p, cp.p);
    }
    void showAinfo(void) {
        cout << num << endl;
        cout << p << endl;
    }
};
 
int main() {
    A ob1(1, "서울시 서초구");
    A ob2 = ob1;
    ob1.showAinfo();
    ob2.showAinfo();
}
 
 
#include<iostream>
using namespace std;
#include"cstring"
 
class Car {
private:
    int engine;
    int pipe;
    int piston;
public:
    Car() : engine(0), pipe(0), piston(0) {} // 생성자 오버로딩시 디폴트 생성자 명시적 정의
    Car(int eg, int pp, int ps) : engine(eg), pipe(pp), piston(ps) { //초기화
     //engine = eg;
     //pipe = pp;
     //piston = ps;
    }
    int get_engine(void) { return engine; }
    int get_pipe(void) { return pipe; }
    int get_piston(void) const { // const - 멤버 변수의 훼손 방지
     //pistone += 20; error!
        return piston;
    }
    void set_engine(int engine) {
        this->engine = engine;// this->engine : 클래스에 있는 엔진(이 때 this는 매개변수로 들어가있는것) = engine : 지역변수 engine
        //this는 호출한 객체자신
    }
    void printf(void) { //printf 는 인라인 함수 , car는 호출 (이때 클래스 밖에 있는 Car에 인라인 함수를 써주면 인라인 함수가 된다.)
        cout << "engine : " << engine << endl;
        cout << "pipe : " << pipe << endl;
        cout << "pistone : " << piston << endl;
    }
};
 
Car::Car(int eg, int pp, int ps) : engine(eg), pipe(pp), piston(ps) { //초기화
//engine = eg;
//pipe = pp;
//piston = ps;
}
 
int add(const int &a, const int& b) {
    return a + b;
}
int main() {
    int a = 10;, b = 20;
    printf("%d", add(a, b));
    printf("%d", add(10, 20)); // 상수값을 받겠다. 그럼 10,20 따로 정의 안해도 됨.
    Car bus1;
    Car bus2(400, 100, 8);
    Car* bus3 = new Car(800, 200, 16);
    cout << bus2.get_engine() << std::endl;
    cout << bus3->get_engine() << std::endl;
    bus2.printf();
    delete bus3;
}
 
- 소멸자
~객체명()
 
#include<iostream>
using namespace std;
#include"cstring"
 
class pos {
private:
    int xpos = 0, ypos = 0;
public:
    pos() :xpos(0), ypos(0) {}
    pos(int x, int y) :xpos(x), ypos(y) {}
    void showposition(void) {
        cout << xpos << ", " << ypos << endl;
    }
    int get_xpos(void) { return xpos; }
    int get_ypos(void) { return ypos; }
};
// 두 위치의 차를 함수 내부에서 힙공간을 만들어 구하고 5와 -2를 가진 힙영역을 리턴한다.
pos& distance_pos(pos& ra, pos& rb) {
    pos* nw = new pos(abs(rb.get_xpos() - ra.get_ypos()),
        abs(rb.get_ypos() - ra.get_ypos()));
    return *nw;
}
class history {
    pos/*&*/ a, b;
public:
 
    history() {}
    history(pos& a, pos& b) :a(a), b(b) {}
 
    history setHistory(pos& a, pos& b) {
        this->a = a;
        this->b = b;
        return *this;
    }
    void showHistory() {
        a.showposition();
        b.showposition();
    }
 
    pos& getA() { return a; }
    pos& getB() { return b; }
    
 
};
int main() {
    pos a(0, 3);
    pos b(5, 1);
 
    pos& rf = distance_pos(a, b);
    // rf를 사용해서 showposition
 
    //인스턴스 a와 b를 함께 저장할 수 있는 history 클래스를 선언하고
    //history클래스형태의 배열 10개중 0번째에 a,b를 저장하시오.
    history* harr = new history[10];
    harr[0].setHistory(a, b).showHistory();
    //harr[0].showHistory();
    delete[] harr;
    return 0;
}
 

- 상품 클래스 만들기
#include<iostream>
using namespace std;
#include <string>
//product 객체가 필요하다
//상품명과 상품가에 대한 속성이 필요하다.(정보은닉의 형태로 구현)
//상품명과 상품가에 대한 출력 서비스와 (출력이니 멤버변수 값이 바뀌지 않아야 한다)
//삼품명과 상품가에 대하 입력 서비스가 필요하다.
//해당 클래스를 선언하고
//main함수에서
 
class product {
private:
    string name;
    int price;
 
public:
    product(){}
    product(string name, int price):name(name),price(price){}
    void input_name_price() {
        cout << "[상품 입력]" << endl;
        cout << "상품명 입력:";
        getline(cin, name);
        cout << "가격 입력:";
        cin >> price;
    }
    void showAll() {
        cout << "[상품 출력]"<< endl;
        cout << "상품명: " << name << endl;
        cout << "가격: " << price << endl;
    }
};
int main() {
    //1. 일반객체 prd1 생성후 해당 상품을 입력(상품명, 상품가)하고
// 출력(상품명, 상품가)해보시오.
    product prd1;
    prd1.input_name_price();
    prd1.showAll();
 
    //2. 동적할당으로 prd2 생성후 입출력 후 마지막에 객체를 할당해제하시오
    product* prd2 = new product("고양이",56789);
    prd2->showAll();
 
    return 0;
}
 
 
- 프랜드
클래스의 private 및 protected 멤버를 자유롭게 접근. 클래스, 함수 단위로 지정가능하다.
댓글
최근에 올라온 글
최근에 달린 댓글
네이버 이웃추가
«   2024/04   »
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
글 보관함