简体   繁体   中英

Dynamic array of class pointers

I'm trying to create a dynamic array of pointers to an amount of instances of a class, ElectricityBill .

My current approach is to create a dynamic array of ElectricityBills (currently with nothing), then create a single instance of an ElectricityBill, create another set of ElectricityBills sized one larger this time, copy all the instances of the old dynamic array across, add the new one at the end.

The code of what I've tried is below

// Define the dyn array
int EBcount = 0;
ElectricityBill **EB = new ElectricityBill*[EBcount];

// Create a temp instance and input the data
ElectricityBill *tempEB = new ElectricityBill;
std::cin >> *tempEB;

std::cout << *tempEB << std::endl;

// Create a new dyn array and copy the instances accross
EBcount++;
ElectricityBill **temp = new ElectricityBill*[EBcount];
for (int i = 0; i < EBcount-1; i++) {
    temp[i] = EB[i];
}

// Append the new instance at the end and delete the old array
temp[EBcount-1] = tempEB;
delete [] EB;
EB = temp;

std::cout << temp[0] << std::endl;
std::cout << EB[0] << std::endl;

and the output is

E;name;1;2;3;acc;add;1/1/2000;1/2/2000;22.721;2.2721
0x100500000
0x100500000

It's worth noting that I've overloaded the operators << and >> within the class definition. The >> operator prompts the user to enter data and stores input data within the class's private section of variables, and the << operator is built like so:

std::ostream& operator<<(std::ostream &stream, ElectricityBill &printStream) {

    stream << "E;"
    << printStream.billerName << ";"
    << printStream.billerCode << ";"
    << printStream.referenceNumber << ";"
    << printStream.accountNumber << ";"
    << printStream.accountName << ";"
    << printStream.address << ";"
    << printStream.periodStartDate.day << "/" << printStream.periodStartDate.month << "/" << printStream.periodStartDate.year << ";"
    << printStream.periodDueDate.day << "/" << printStream.periodDueDate.month << "/" << printStream.periodDueDate.year << ";"
    << printStream.amountDue << ";"
    << printStream.totalGST;

    return stream;
}

For some reason, the output is outputting memory addresses instead of the expected data. Why is this happening and what can I do to fix it?

Your overloaded operatator accepts a reference to an ElectricityBill, but you appear to be providing a pointer. Hence, the default implementation for << is being used, which prints the memory location. Try:

std::cout << *temp[0] << std::endl;
std::cout << *EB[0] << std::endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM