简体   繁体   中英

error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’}

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'})

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-

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM