首页 > 解决方案 > 无法理解如何将对象添加到动态数组并在 C++ 中打印它们

问题描述

我正在尝试测试代码以创建一个动态数组,该数组接受来自 phonebook2.txt 文件的不同类型的对象。我目前无法理解为什么代码无法运行。在尝试添加 printMyArray 方法后,我收到了很多错误消息。任何帮助都是极好的。

我知道如何使用向量来做到这一点,但我必须使用 new 运算符创建一个动态数组。

/*PATRICIA JOHNSON 973437
LINDA WILLIAMS 3532665
BARBARA BROWN 4059171
ELIZABETH JONES 2736877
JENNIFER MILLER 3863726
MARIA DAVIS 6297086
SUSAN GARCIA 6063076
MARGARET RODRIGUEZ 350662
DOROTHY WILSON 2829644
LISA MARTINEZ 6299105*/
class Contact {
    private:
        string firstName;
        string lastName;
        int phoneNumber;

    public:
        Contact(){};
        Contact(string, string, int);

        string getFirstName() {
            return firstName;
        }

        string getLastName() {
            return lastName;
        }

        int getPhoneNumber() const {
            return phoneNumber;
        }
}
#include "Contact.h"
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

void printMyArray(Contact* arr) {
    for (int i = 0; i < 50; i++) {
        cout << arr[i].getFirstName() << " " << arr[i].getLastName() << " " << arr[i].getPhoneNumber() << endl;
    }
}

int main() {
    Contact *contactsArray = new Contact[50];
    ifstream inFile("phonebook2.txt");

    int i;

    string firstName;
    string lastName;
    int pnum;

    while (inFile >> firstName >> lastName >> pnum) {
        cout << firstName << " " << lastName << " " << pnum << endl;
        Contact c(firstName, lastName, pnum);
        contactsArray[i] = c;
        i++;
    }

    for (int i = 0; i < 50; i++) {
        cout << contactsArray[i] << endl;
    }
    
    printMyArray(contactsArray);

    delete[] contactsArray;
    
    return 0;
}

Some error messages: 

main.cpp:24:5: error: 'printMyArray' was not declared in this scope
     printMyArray(contactsArray);

undefined reference to `Contact::Contact(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)'
collect2.exe: error: ld returned 1 exit status

标签: c++arraysoopobject

解决方案


为您的输入建模一个结构:

struct Record
{
  string first_name;
  string last_name;
  string phone_number;
};

接下来,重载以从输入流operator>>中读取 a :Record

    struct Record
    {
      string first_name;
      string last_name;
      string phone_number;
      friend std::istream& operator>>(std::istream& input, Record& r);
    };
std::istream& operator>>(std::istream& input, Record& r)
{
  input >> r.first_name;
  input >> r.last_name;
  input >> r.phone_number;
  input.ignore(1000000, '\n');
  return input;
}

将您的记录读入数据库:

std::vector<Record> database;
Record r;
while (input_file >> r)
{
  database.push_back(r);
}

简化你的生活,不要使用静态数组或动态数组。std::vector是一个将根据需要调整大小的数组。您无需编写代码来分配数组、检查溢出、分配新数组、将旧数组复制到新数组、删除旧数组。


推荐阅读