samedi 19 mars 2022

Object C++ tab[i] new object values assign

When I try to assign values in main() to tab[i] I get memory leak. You can change anything in code, but class need to stay as string, string, double and "K2 tab[4];" stay as it is. Under main() you have a view on data.txt file.

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

class K2 {
    string* words;
    double number;

public:
    K2() :words(nullptr), number(0.0) {}
    K2(const string& a1, const string& a2, const double& a3) :number(a3) {
        words[0] = a1;
        words[1] = a2;
    }

    K2& operator=(const K2& r) {
        words[0] = r.words[0];
        words[1] = r.words[1];
        number = r.number;
        return *this;
    }

friend
ostream& operator<<(ostream& out, const K2& r);
};
ostream& operator<<(ostream& out, const K2& r) {
    return out << r.words[0] << " " << r.words[1] << " " << r.number << endl;
}

int main() {
    K2 tab[4];

    string a, b;
    double c;
    ifstream file;
    file.open("data.txt");
    for (int i = 0; i < 4; i++) {
        file >> a >> b >> c;
        tab[i] = K2 (a, b, c); // <- memory leak
    }
    file.close();
}
/*
data.txt:
white coffe 3.50
black tea 1.50
orange juice 3.00
dark chocolate 5.25
*/

Aucun commentaire:

Enregistrer un commentaire