如何打印类中嵌套类信息?入队程序客户信息打印异常排查
Hey there, that weird output like 1Senior @ (age 4508754) is a clear sign your program is accessing invalid memory or has incorrect object handling. Let's walk through the most likely causes and fixes:
1. You're Storing Dangling Pointers/References in the Queue
If your CustomerQueue uses a container of Customer* or Customer& instead of value objects (Customer), you might be adding pointers to local Customer instances that get destroyed right after being enqueued. When you later try to print, those pointers point to deallocated memory, leading to garbage values like that random age number.
Fix:
- Switch to storing value objects directly, e.g., use
std::queue<Customer>as your underlying container. This ensures each enqueuedCustomeris fully copied into the queue, with its own valid memory. - If you must use pointers, use smart pointers like
std::unique_ptr<Customer>orstd::shared_ptr<Customer>to manage object lifetimes automatically.
2. Missing or Incorrect Copy Semantics in the Customer Class
If your Customer class has members that require deep copying (like dynamically allocated C-style strings), the compiler-generated default copy constructor/assignment operator will only do a shallow copy. This can lead to invalid memory access or corrupted member values when objects are copied into the queue.
Example Fix for Custom Copy Logic:
#include <cstring> enum CustomerType { Senior, Regular, VIP }; class Customer { private: char* name; // Dynamic string requires deep copy int age; CustomerType type; public: // Constructor Customer(const char* customerName, int customerAge, CustomerType customerType) : age(customerAge), type(customerType) { name = new char[strlen(customerName) + 1]; strcpy(name, customerName); } // Explicit copy constructor for deep copy Customer(const Customer& other) : age(other.age), type(other.type) { name = new char[strlen(other.name) + 1]; strcpy(name, other.name); } // Explicit assignment operator Customer& operator=(const Customer& other) { if (this != &other) { // Clean up existing memory first delete[] name; // Deep copy the new data name = new char[strlen(other.name) + 1]; strcpy(name, other.name); age = other.age; type = other.type; } return *this; } // Destructor to clean up dynamic memory ~Customer() { delete[] name; } // Getters for printing const char* getName() const { return name; } int getAge() const { return age; } CustomerType getType() const { return type; } };
3. Invalid Object Initialization in main
Double-check how you're creating Customer instances before enqueuing them. If you're passing an uninitialized variable for the age parameter (e.g., int age; Customer c("Alice", age, Senior);), that uninitialized age will hold a random garbage value that gets stored in the queue.
Fix:
Always ensure all parameters passed to Customer constructors are properly initialized before use.
4. Bug in Your Printing Logic
It's possible your queue's print function is accessing the Customer members incorrectly. For example, you might accidentally print the memory address of a Customer pointer instead of the age member, or have an off-by-one error in mapping your CustomerType enum to strings.
Example of a Broken vs Fixed Print Function:
// Broken: Prints pointer address instead of age void CustomerQueue::printQueue() { Customer* current = queue.front(); // If using pointers cout << "1Senior @ (age " << current << ")" << endl; // Oops! current is a pointer } // Fixed: Accesses the age member correctly void CustomerQueue::printQueue() { // If storing value objects: Customer current = queue.front(); // Map enum to string const char* typeStr = ""; switch(current.getType()) { case Senior: typeStr = "Senior"; break; case Regular: typeStr = "Regular"; break; case VIP: typeStr = "VIP"; break; } cout << current.getType() << typeStr << " @ (age " << current.getAge() << ")" << endl; }
Start by checking which of these scenarios matches your code—my bet is either dangling pointers or missing copy semantics are the root cause!
内容的提问来源于stack exchange,提问作者skyzhuzhu

