1
votes

the code on monte_carlo.hpp is :

class Histogramme{
    protected:
        std::vector<double> echantillon;
        unsigned int nb_boxes;
        double lbound;
        double ubound;
        double box_width;
    public:
        Histogramme(double min_intervalle, double max_intervalle, unsigned int n) : nb_boxes(n), lbound(min_intervalle),
        ubound(max_intervalle), box_width((max_intervalle - min_intervalle)/n),echantillon(n) {}
        Histogramme& operator+=(double x);
        Histogramme& operator/=(double n);
        friend std::ostream& operator<<(std::ostream&, const Histogramme &);
};

And in monte_carlo.cpp :

std::ostream& operator<<(std::ostream& o,const Histogramme& H){
    for(int i=0; i<H.echantillon.size(); i++){ o << H.echantillon.size() << std::endl;}
    return o;
}

I don't understand why the operator << doesn't work when i remove the "const" at the Histogramme parameter, the error is :

error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream’} and ‘std::vector::size_type’ {aka ‘long unsigned int’})

1
Can you please post how do you use it in your code?Tiger Yu
Are you really outputing the same value (the size of the vector) in a loop on purpose?Dmitry Kuzminov
Are you removing const from both definition and friend declaration at the same time?Dmitry Kuzminov
As others have already asked: If your removing the const only in one place that function wont be friend anymore which will prevent access to echantillon. This could often result in such a misleading error message as above.Sebastian Hoffmann
The posted code seems to be far from the real one, we don't see Histogram::sample.S.M.

1 Answers

1
votes

I delete "const" from the Histogram parameter in the friend function and in the function declaration, the error message is no longer there

Great

But I get the error message " error: 'std::vector Histogram::sample' is protected within this context"

I'm not getting any errors with or without the const. here is what I wrote:

#include <iostream>
#include <vector>
//using namespace std;

class Histogramme {
protected:
    std::vector<double> echantillon;
    unsigned int nb_boxes;
    double lbound;
    double ubound;
    double box_width;
public:
    Histogramme(double min_intervalle, double max_intervalle, unsigned int n) : 
        nb_boxes(n), lbound(min_intervalle),
        ubound(max_intervalle), box_width((max_intervalle - min_intervalle) / n), echantillon(n) {}
    Histogramme& operator+=(double x)
    {
        ;
    }
    Histogramme& operator/=(double n)
    {
        ;
    }
    friend std::ostream& operator<<(std::ostream&, Histogramme&);
};

std::ostream& operator<<(std::ostream& o, Histogramme& H) {
    for (int i = 0; i < H.echantillon.size(); i++)
    {
        o << H.echantillon.size() << std::endl;
    }
    return o;
}

int main()
{
    Histogramme example(0.3, 34.2, 5);

    std::cout << example << std::endl;
    return 0;
}

https://godbolt.org/z/HaQQR-