Studies/C++
08 클래스(2)-생성자와 소멸자
쿠뱃봉
2022. 1. 28. 18:39
1.Point 클래스
(1)Point.h
#pragma once
class Point
{
private:
int x;
int y;
public:
~Point(); //소멸자
Point();
Point(const int& X, const int& Y);
void init(const int& X, const int& Y);
void setXY(const int& X, const int& Y);
void move(const int& dist);
void showPoint() const;
int getX() const;
int getY() const;
};
(2)Point.cpp
#include "Point.h"
#include<iostream>
using namespace std;
Point::~Point() {
cout << "포인트 소멸자" << endl;
}
Point::Point()
:x(0),y(0)
{
cout << "디폴트 생성자" << endl;
}
Point::Point(const int& X, const int& Y)
:x(X),y(Y)
{
cout << "인자있는 생성자" << endl;
}
void Point::move(const int& dist) {
x += dist;
y += dist;
}
void Point::init(const int& X, const int& Y) {
x = X;
y = Y;
}
void Point::showPoint() const {
cout << x << "," << y << endl;
}
int Point::getX()const {
return x;
}
int Point::getY()const {
return y;
}
2.Rectangle 클래스
(1)Rectangle.h
#pragma once
#include"Point.h"
class Rectangle
{
private:
Point LT;
Point RB;
public:
~Rectangle();
Rectangle();
Rectangle(const int& x1, const int& y1, const int&x2, const int& y2);
void init(const int& x1,const int& y1,const int&x2,const int& y2);
void showRectangle()const;
Point getLT() const;
Point getRB() const;
int getArea(const Point& LT, const Point&RB);
};
(2)Rectangle.cpp
#include "Rectangle.h"
#include<iostream>
using namespace std;
Rectangle::~Rectangle() {
cout << "Rectangle 소멸자" << endl;
}
Rectangle::Rectangle()
:LT(100,100),RB(200,200)
{
cout << "Rectangle 디폴트 생성자" << endl;
LT.init(100, 100);
RB.init(100, 100);
}
Rectangle::Rectangle(const int& x1, const int& y1, const int&x2, const int& y2)
:LT(x1,y1),RB(x2,y2)
{
cout << "Rectangle 인자있는 생성자" << endl;
}
void Rectangle:: init(const int& x1, const int& y1, const int&x2, const int& y2) {
LT.init(x1, y1);
RB.init(x2, y2);
}
void Rectangle::showRectangle()const {
LT.showPoint();
RB.showPoint();
}
Point Rectangle::getLT() const {
return LT;
}
Point Rectangle::getRB() const {
return RB;
}
int Rectangle::getArea(const Point& LT, const Point&RB) {
return (RB.getX() - LT.getX())*(RB.getY() - LT.getY());
}
3. main 함수
#include<iostream>
#include"Rectangle.h"
using namespace std;
void move(Point& pt, const int& dist) {
pt.move(dist);
}
int main() {
//Point pt1;
//pt1.init(100, 100);
//pt1.showPoint();
//move(pt1, 10);
//Rectangle rect;
//rect.init(100, 100, 200, 200);
//rect.showRectangle();
//Point pt;
//Point pt2(10, 20);
//Point* p = new Point();
//delete p;
Rectangle rect(100, 100, 200, 200);
return 0;
}