1

I am a learning c++ and have a class project due in 5 days. I've spent 4 hours researching how to do this however I have not come up with an answer yet. Save me stack!

Problem. I have a pointer to a class which holds a dynamic array. I need to take that array and save it to a file to retrieve later. Here are my 2 headers and the implementation. I am not writing the code to "save to file" yet as that will be easy once I get around this issue. My problem is it keeps printing the address of the pointer and not the data within.

vehReg.h

class vehReg {
    public:
        /* STUFF */
    };
}
#endif

vehData.h

#include "vehReg.h"

using namespace std;

class vehData {
    public:
        //CONSTRUCTORS
        vehData();

        //DECONSTRUCTOR
        ~vehData();

        //METHODS
        friend ostream &operator<<( ostream &output, const vehData &v);

    private:
        typedef unsigned long longType;
        typedef std::size_t sizeType;
        sizeType used,capacity;
        vehReg *data;
    };
}
#endif

vehData.cpp

    //CONSTRUCTOR
    vehData::vehData(){
        capacity = 5;
        used = 0;
        data = new vehReg[capacity];
    }

    //DECONSTRUCTOR
    vehData::~vehData(){
        delete []data;
    }

    /* TRYING TO ACCOMPLISH THIS WITH AN OSTREAM OVERLOAD */
    void vehData::saveDataSloppy(){
        ofstream myFile;
        myFile.open ("database.db");
        for(int i=0;i<used;i++){
            myFile << data[i].getOwnerName() << "|";
            myFile << data[i].getVehicleLicense() << "|";
            myFile << data[i].getVehicleMake() << "|";
            myFile << data[i].getVehicleModel() << "|";
            myFile << data[i].getVehicleYear() << "\n";
        }
        myFile.close();
}

    void vehData::saveData(){
        cout << data;
    }

    ostream &operator<<(ostream &stream, const vehData &v){
        stream << v.data;
    }
}
4

2 回答 2

2

v.data是一个指针,所以它打印一个指针。您希望它如何打印指针指向的任何内容。除了字符指针,<<总是打印你给它的东西(以某种方式格式化)。如果您不希望它打印指针,请给出其他内容。

假设它确实取消了指针的引用。它应该打印什么:一个 vehReg?20?指针没有关于大小的信息。如果您使用过std::vector<vehReg>(更好的选择),它会知道大小,但仍然没有过载std::vector,因为系统仍然不知道您希望它如何格式化(逗号分隔?每个都在新行上?)。而且您还没有告诉它如何打印vehReg

您显然了解如何重载的想法<<。您必须做的第一件事是也提供一个重载vehReg。并且两个重载都必须根据现有的重载来定义:没有一个 for std::vector,一个 for 指针不能做你想做的事(也不能做),所以你必须循环你的<<for vehData并输出每个元素,使用您决定的任何分隔符。(如果每个元素都在自己的行上,那么您可以使用std::copy and 一个ostream_iteratorfor 循环,但这可能比您目前所学的内容提前一点。)然后转发到<<for vehRegfor each vehReg

于 2012-09-13T19:18:51.357 回答
0

v.data是一个指针,所以它是一个内存地址。

*v.data是指针指向的内容(在这种情况下是整数)。

例如,

#include <iostream>

using namespace std;

void main () { 
int *ptr; 
int var = 5;
ptr = &var;
cout << ptr << endl;
cout << *ptr << endl;
system("pause");
}

第一行将打印出如下内容:0043F930

第二行将打印出:5

这应该打印出数据数组中保存的元素。

void vehData::showStructure() const {
    for (int i = 0; i < capacity: i++) {
         cout << data[i];
    }
    cout << endl;
}
于 2012-09-13T20:13:30.283 回答