생성자,소멸자, 멤버 이니셜라이저.
[ C++ ] 생성자와 소멸자 그리고 멤버 이니셜라이저( Member Initializer )
생성자(constructor)는 객체 생성 시 딱 한번 호출된다. 또한 클래스의 이름과 함수의 이름이 동일하고 반환형이 선언되어 있지 않으며, 실제로 반환하지 않는다. 또한 생성자도 함수이기에 오버
musket-ade.tistory.com
https://morning97.tistory.com/37?category=1001665
[c++] const함수와 멤버이니셜라이저(+this)
코드작성할때 사용자가 아무거나 막 바꿔서 사용하면 오류가 날 수도 있고, 바뀌지말았으면 하는것들이 생겨날것이다. 이때 못바꾸게 지정하는 함수가 있는데 그게 바로 const 함수이다. const 함
morning97.tistory.com
TV)
#include<iostream>
using namespace std;
class TV {
private:
const int PRICE;
int ch;
int vol;
bool power;
public:
TV(int ch, int vol, int price); //이니셜라이저 할 생성자 함수 선언
~TV();
void powerOn(void);
void powerOff(void);
void setTv(int ch, int vol); // price는 const떄매 수정 못함, 수정 시 에러.
void showTvInform(void);
};
TV::TV(int ch, int vol, int price) : PRICE(price) //이니셜라이저
{
{
cout << "생성자 생성" << endl;
this->ch = ch;
this->vol = vol;
this->power = false;
}
}
void TV::powerOn(void)
{
cout << "==========TV ON==========" << endl;
power = true;
}
void TV::powerOff(void)
{
cout << "==========TV OFF==========" << endl;
power = false;
}
TV::~TV(void)
{
cout << "생성자 소멸" << endl;
}
void TV::showTvInform(void)
{
cout << "channel: " << ch << endl;
cout << "volume: " << vol << endl;
cout << "price: " << PRICE << endl;
cout << "전원여부: " << power << endl;
}
void TV::setTv(int ch, int vol)
{
this->ch = ch;
this->vol = vol;
}
int main(void)
{
TV tv(3, 10, 1000);
tv.powerOn();
tv.showTvInform();
tv.setTv(5, 100);
tv.showTvInform();
tv.powerOff();
tv.showTvInform();
}
사각형 넓이 예제 ( 내 코드 ) // 멤버이니셜라이저 사용을 못했음. 익숙해지자.
#include<iostream>
using namespace std;
class Rect
{
private:
double x1;
double x2;
double y1;
double y2;
double width;
double height;
public:
Rect(double x1, double x2, double y1, double y2)
{
this->x1 = x1;
this->x2 = x2;
this->y1 = y1;
this->y2 = y2;
}
void showRect()
{
cout << "width: " <<(int) width << endl;
cout << "height: " << (int)height << endl;
}
double Area()
{
this->width = y2 - y1;
this->height = x2 - x1;
return width*height;
}
};
int main(void)
{
Rect rectangle(10, 20, 5, 20);
rectangle.Area();
rectangle.showRect();
cout << "면적" << endl;
cout << rectangle.Area()<<endl;
system("pause");
}
모범 코드(예제 그대로)
#include<iostream>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point(int x, int y)
{
this->x = x;
this->y = y;
}
int getX() const
{
return x;
}
int getY()const
{
return y;
}
};
class Rectangle {
private:
Point lowLeft;
Point upRight;
public:
Rectangle(int x1, int y1, int x2, int y2):lowLeft(x1,y1),upRight(x2,y2){} // Rectangle클래스의 int x1, x2 ...인자들이 Point 클래스의 lowLeft, upRight 인자들 x1,y1,x2,y2에 할당됨
int getRectArea()const
{
int width = upRight.getX() - lowLeft.getX();
int height = upRight.getY() - lowLeft.getY();
// 절댓값
if (width < 0)
width =- width;
if (height < 0)
height= - height;
return width*height;
}
};
int main(void)
{
Rectangle nemo(10, 10, 5, 20);
cout << "면적: " << nemo.getRectArea() << endl;
system("pause");
}