我有一个Readf函数,我试图调用它在每个构造函数中填充一个数组,我只尝试了使用带有代码语句ReadF(cap,* point,counter);的默认构造函数。

第二个参数是找出问题的原因,我会在旁边带有'&'或''的地方出现错误。而且我的'*'出现外部错误,我还是c ++的新手,所以我没有处理类的经验。

我必须使用ReadF成员函数,还有其他方法可以代替它调用以获得我需要的结果。

另外,我拥有的某些功能的代码可能并不完美,但是在继续讨论之前,我想先解决此问题。

array.h:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class AR {
public:
    AR();
    AR(int);
    AR(const AR&);
    //~AR();

    void ReadF(const int, string&, int);
    AR& operator=(const AR&);

    friend ostream& operator<<(ostream&, AR&);
    friend ifstream & operator>>(ifstream&, AR&);

private:
    string* point;
    int counter;
    int cap;
};


array.cpp:

#include "array.h"


AR::AR() {
    counter = 0;
    cap = 2;
    point = new string[cap];
}

AR::AR(int no_of_cells) {
    counter = 0;
    cap = no_of_cells;
    point = new string[cap];
}

AR::AR(const AR& Original) {
    counter = Original.counter;
    cap = Original.cap;
    point = new string[cap];

    for(int i=0; i<counter; i++) {
        point[i] =Original.point[i];
    }
}

// AR::~AR() {
//  delete [ ]point;
//}

ostream& operator<<(ostream& out, AR& Original) {
    cout << "operator<< has been invoked\n";
    for (int i=0; i< Original.counter; i++) {
        out << "point[" << i <<"] = " << Original.point[i] << endl;
    }
    return out;
}

AR& AR::operator=(const AR& rhs) {
    cout << "operator= invoked\n";
    if (this == &rhs)
        return *this;
    point = rhs.point;
    return *this;
}

void ReadF(const int neocap, string& neopoint, int neocounter) {

    ifstream in;
    in.open("sample_strings.txt"); //ifstream in;  in.open("sample_data.txt");

    if (in.fail())
        cout<<"sample_data not opened correctly"<<endl;

    while(!in.eof() && neocounter < neocap) {
        in >> neopoint[neocounter];
        neocounter++;
    }

    in.close();
}


ifstream& operator>>(ifstream& in, AR& Original) {
    Original.counter = 0;

    while(!in.eof() && Original.counter < Original.cap) {
        in >> Original.point[Original.counter];
        (Original.counter)++;
    }

    return in;
}

最佳答案

似乎您在ReadF定义中缺少AR ::。

再次考虑,您正在阅读可能尚未分配的neopoint索引。您可以将ReadF更改为:

void ReadF(const int neocap, string& neopoint,int neocounter)
{

    ifstream in;
    in.open("sample_strings.txt"); //ifstream in;  in.open("sample_data.txt");

    if (in.fail())
    {
        cout<<"sample_data not opened correctly"<<endl;
        return;
    }

    neopoint.resize(neocap);

    while(neocounter < neocap && in >> neopoint[neocounter])
    {
        neocounter++;
    }

    in.close();
}


虽然您可能想研究stringstream

std::ifstream in("sample_strings.txt");

if (in)
{
    std::stringstream buffer;
    buffer << in.rdbuf();
    in.close();
    inneopoint= buffer.str();
}

09-10 19:27