[c++] 구조체와 클래스의 다른 클래스 포함
C++에서 구조체(struct)와 클래스(class)는 모두 데이터 멤버와 멤버 함수를 포함할 수 있는 사용자 정의 데이터 타입이다. 둘 다 서로를 포함하여 복합적인 데이터 구조를 만들 수 있지만, 이 둘 사이에는 몇 가지 중요한 차이점이 있다.
구조체(struct)의 클래스 포함
구조체는 다른 클래스를 포함하여 복합 데이터 타입을 만들 수 있다. 이를 통해 다른 클래스의 인스턴스를 구조체의 멤버로 사용할 수 있다. 예를 들어, 다음은 구조체가 클래스를 포함하는 예시이다.
#include <iostream>
class Point {
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
};
struct Rectangle {
int width, height;
Point topLeft;
Rectangle(int width, int height, const Point& topLeft) : width(width), height(height), topLeft(topLeft) {}
};
int main() {
Point point(3, 4);
Rectangle rect(100, 200, point);
std::cout << "Width: " << rect.width << ", Height: " << rect.height << ", TopLeft: (" << rect.topLeft.x << ", " << rect.topLeft.y << ")" << std::endl;
return 0;
}
클래스(class)의 클래스 포함
클래스 또한 다른 클래스를 포함할 수 있다. 이때, 포함된 클래스의 객체는 포함하는 클래스의 일부가 된다. 다음은 클래스가 다른 클래스를 포함하는 예시이다.
#include <iostream>
class Engine {
public:
void start() {
std::cout << "Engine started" << std::endl;
}
};
class Car {
public:
Engine engine;
void start() {
engine.start();
std::cout << "Car started" << std::endl;
}
};
int main() {
Car myCar;
myCar.start();
return 0;
}
결론
구조체와 클래스는 모두 다른 클래스를 포함하여 복합 데이터 구조를 만들 수 있으며, 이를 통해 코드의 모듈화와 재사용성을 높일 수 있다. 과연 둘 중 어떤 것을 사용할지는 프로그램의 요구사항과 개발자의 개별적인 선택에 달려있다.
이러한 포함 관계를 통해 객체 지향 프로그래밍(OOP)의 강력한 기능을 활용할 수 있다.
참고 자료
- cplusplus.com - Classes (C++ documentation)
- GeeksforGeeks - Difference between Structure and Class in C++