/* * This program makes use of a trivial C++ class in order to point out * some basic syntax and other issues. */ #include #include using namespace std; /* * This class represents an integer value with a label for printing. */ class LabeledInt { public: // Create an object. LabeledInt(string label, int value = 0) { m_label = label; m_value = value; } // Get the labeled value for easy printing string to_string() const { return m_label + ": " + std::to_string(m_value); } // Change the label. void relabel(string label) { m_label = label; } // Get or set the value. int get() const { return m_value; } void set(int value) { m_value = value; } private: string m_label; int m_value; }; void munge(LabeledInt ll) { ll.relabel("Nothing"); ll.set(0); } void set(LabeledInt & ll) { ll.relabel("something"); ll.set(99); } int main() { // Make some. LabeledInt li1("Peanuts", 487); LabeledInt li2("Acorns", 9871); LabeledInt li3("Marbles"); // Print them. cout << "A " << li1.to_string() << ", " << li2.to_string() << ", " << li3.to_string() << endl; // Some pretty random changes. li1.set(li1.get() + 13); li3.set(17); li2.set(li3.get() * li1.get()); // Print them. cout << "B " << li1.to_string() << ", " << li2.to_string() << ", " << li3.to_string() << endl; // Compare to Java. LabeledInt cpy = li1; li1.set(3); li1.relabel("Pebbles"); li2 = li3; li2.set(3*li2.get()); // Print them. cout << "C " << li1.to_string() << ", " << li2.to_string() << ", " << li3.to_string() << ", " << cpy.to_string() << endl; // Note that each function uses a different parameter passing method. munge(li1); set(li2); // Print them. cout << "D " << li1.to_string() << ", " << li2.to_string() << ", " << li3.to_string() << endl; }