【问题标题】:error: no match for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’}错误:'operator<<' 不匹配(操作数类型是'std::ostream' {aka'std::basic_ostream<char>'}
【发布时间】:2020-08-18 13:45:12
【问题描述】:

monte_carlo.hpp 上的代码是:

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 &);
};

在 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;
}

我不明白为什么当我在 Histogramme 参数中删除“const”时运算符

错误:'operator

【问题讨论】:

  • 你能在你的代码中发布你如何使用它吗?
  • 你真的是故意在循环中输出相同的值(向量的大小)吗?
  • 您是否同时从定义和friend 声明中删除const
  • 正如其他人已经问过的那样:如果您仅在一个地方删除 const,则该函数将不再是朋友,这将阻止访问 echantillon。这通常会导致上述误导性错误消息。
  • 贴出的代码似乎与真实的相差甚远,我们看不到 Histogram::sample。

标签: c++


【解决方案1】:

我在友元函数和函数声明中的Histogram参数中删除“const”,错误信息不再存在

很棒

但我收到错误消息“错误:'std::vector Histogram::sample' is protected within this context”

无论有没有const,我都没有收到任何错误。这是我写的:

#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-

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多