해당 챕터에서는 객체와 자료구조의 차이점, 어떠한 상황에서 어떠한 방식을 사용해야하는지 등에 대해 기술한다.
자료구조 (구조체)
struct Point {
int x;
int y;
}
객체 (class)
// 객체
class Point {
public:
int getX();
void setX(int x);
int getY();
void setY(int y);
private:
int x;
int y;
}
...
class Shape {
public:
virtual double area() const = 0;
// ...(함수 추가)
virtual ~Shape() {}
};
class Circle : public Shape {
double radius;
public:
Circle(double r) : radius(r) {}
double area() const override {
return M_PI * radius * radius;
}
};
class Rectangle : public Shape {
double width, height;
public:
Rectangle(double w, double h) : width(w), height(h) {}
double area() const override {
return width * height;
}
};
void printTotalArea(const std::vector<std::shared_ptr<Shape>>& shapes) {
double total = 0;
for (const auto& s : shapes)
total += s->area();
std::cout << "Total area: " << total << "\n";
}
...
장점
단점
...
enum class ShapeType {
CIRCLE,
RECTANGLE
};
struct Shape {
ShapeType type;
union {
struct { double radius; };
struct { double width, height; };
};
};
double computeArea(const Shape& s) {
switch (s.type) {
case ShapeType::CIRCLE:
return M_PI * s.radius * s.radius;
case ShapeType::RECTANGLE:
return s.width * s.height;
default:
return 0.0;
}
}
장점