Box Volume
Define a Box struct with member variables length, width, and height. Create a get_volume function and then overload the > operator to compare the volumes of two Box objects. Create instances of Box, compare their volumes using the > operator, and print the result.
Answer
#include <iostream>
struct Box {
float length;
float width;
float height;
// Constructor with parameters
Box(float l, float w, float h) : length(l), width(w), height(h) {}
// Function to calculate the volume of the box
float get_volume() const {
return length * width * height;
}
// Overload the > operator to compare the volumes of two Box objects
bool operator>(const Box& other) const {
return get_volume() > other.get_volume();
}
void display_dimensions() const {
std::cout << "Length: " << length << ", Width: " << width << ", Height: " << height << std::endl;
std::cout << "Volume: " << get_volume() << std::endl;
}
};
int main() {
// Creating instances of Box
Box box1(3.0, 4.0, 5.0);
Box box2(2.0, 3.0, 6.0);
// Display dimensions and volumes
std::cout << "Box 1:" << std::endl;
box1.display_dimensions();
std::cout << std::endl;
std::cout << "Box 2:" << std::endl;
box2.display_dimensions();
std::cout << std::endl;
// Comparing volumes using the > operator
if (box1 > box2) {
std::cout << "Box 1 has a greater volume than Box 2." << std::endl;
} else {
std::cout << "Box 1 does not have a greater volume than Box 2." << std::endl;
}
return 0;
}