C++/문제풀이
[C++] 클래스 작성 연습.cpp
year.number
2022. 6. 30. 16:22
문제 1.
상품의 재고를 나타내는 클래스를 작성하여 보자. 클래스 안에 상품 번호, 재고 수량이 멤버 변수로 저장되고 재고를 증가, 감소하는 멤버함수를 작성하여 보라.
#include <iostream>
using namespace std;
class Product{
public:
//멤버 변수 정의
int id;
int numOfProduct;
//멤버 함수 정의
void ProductAdd(){
numOfProduct++;
}
void ProductMinus(){
numOfProduct--;
}
Product(int i = 202112454, int nop = 23) : id(i), numOfProduct(nop){}
};
int main(){
Product obj_product;
cout << "함수 호출 전: ";
cout << obj_product.id << " - " << obj_product.numOfProduct;
cout << endl;
cout << "함수 호출 후: ";
obj_product.ProductAdd();
obj_product.ProductAdd();
cout << obj_product.id << " - " << obj_product.numOfProduct;
cout << endl;
return 0;
}
문제 2.
2차원 공간에서 하나의 점을 나타내는 Point 클래스를 작성하여 보자.
#include <iostream>
#include <string>
using namespace std;
//step 1. 클래스 생성
class Point{
int x;
int y;
public:
int getX();
int getY();
void setX(int xCoord);
void setY(int yCoord);
void print(int getX, int getY);
};
//멤버 함수의 외부 정의
int Point::getX(){
return x;
}
int Point::getY(){
return y;
}
void Point::setX(int xCoord){
x = xCoord;
}
void Point::setY(int yCoord){
y = yCoord;
}
void Point::print(int px, int py){
cout << px << ", " << py ;
}
int main(){
Point p1;
p1.setX(100);
p1.setY(200);
int x = p1.getX();
int y = p1.getY();
p1.print(x, y);
}
다르게 출력하는 방법
void Point::print(int px, int py){
x = px;
y = py;
cout << "x 좌표는: " << x << "이고, y 좌표는: " << y << "이다.";
}
. . .
p1.print(100, 200);