← Back to Question List
C++ Code Walkthrough #83
Three Files: An Aggregation That Shows Later Changes
📄 Code
Read carefully — what does this print?1// ===== Part.h =====2#ifndef PART_H3#define PART_H4#include <iostream>56class Part {7 int m_id;8 int m_qty;9public:10 Part(int id, int qty) : m_id(id), m_qty(qty) {}11 void setQty(int qty) { m_qty = qty; }12 friend std::ostream& operator<<(std::ostream& os, const Part& p) {13 return os << "#" << p.m_id << " x" << p.m_qty;14 }15};1617#endif1819// ===== Kit.h =====20#ifndef KIT_H21#define KIT_H22#include <iostream>23#include "Part.h"2425class Kit {26 const Part* m_parts[4];27 int m_count = 0;28public:29 Kit& operator+=(const Part& part) {30 for (int i = 0; i < m_count; i++) {31 if (m_parts[i] == &part) {32 return *this;33 }34 }35 m_parts[m_count] = ∂36 m_count++;37 return *this;38 }39 friend std::ostream& operator<<(std::ostream& os, const Kit& kit) {40 static int printed = 0;41 printed++;42 os << "Kit " << printed << " (" << kit.m_count << ")" << std::endl;43 for (int i = 0; i < kit.m_count; i++) {44 os << " " << *kit.m_parts[i] << std::endl;45 }46 return os;47 }48};4950#endif5152// ===== main.cpp =====53#include <iostream>54#include "Kit.h"55using namespace std;5657int main() {58 Part bolt(1, 10), nut(2, 20);59 Part bolt2(1, 10);60 Kit kit;61 kit += bolt;62 kit += nut;63 kit += bolt;64 kit += bolt2;65 cout << kit;66 bolt.setQty(99);67 cout << kit;68 return 0;69}