首页 > 解决方案 > 带有 const onject 的 std::vector 不可访问性

问题描述

我试图重载直方图类的 << 运算符,其头文件是:

#ifndef HISTOGRAM_H
#define HISTOGRAM_H
#include<bits/stdc++.h>

class Histogram{
    private:
        std::vector<float>   listOfElements;
        std::vector<float>  sortedListOfElements;
        std::vector<float>  bucketValues;
        std::vector<float>  bucketFrequencies;
        int numberOfBuckets;
        void setSortedListOfElements();
        void setBucketValues();
        void setBucketFrequencies();
        

    public:
        Histogram(std::vector<float>, int = 10);
        Histogram(const Histogram &obj);
        ~Histogram();

        

        std::vector<float> getListOfElements();
        std::vector<float> getSortedListOfElements();
        std::vector<float> getBucketValues();
        std::vector<float> getBucketFrequencies();
        friend ostream& operator<<(ostream &out, const Histogram &hs);

        static float truncfn(float x);

};

这是我尝试过的,在Histogram.cpp

ostream & operator<< (ostream &out, const Histogram &hs){
        out.precision(4);
        out<<fixed;
        int k;
        vector<float>vals = hs.bucketValues;
        vector<float>freq = hs.bucketFrequencies;
        for(k = 0; k<10; k++){
            out<<showpoint<<hs.truncfn(vals[k])<<",";
        }
        out<<showpoint<<hs.truncfn(vals[k])<<" ";
        int j;
        for(int j = 0; j < 9; j++){
            out<<showpoint<<hs.truncfn(freq[j])<<",";
        }
        out<<showpoint<<hs.truncfn(freq[j]);
        return out;
}

但是,bucketValues并且bucketFrequencies无法从此 const 对象 hs 访问。我该如何解决这个问题?
我需要函数参数有一个 const,因为这个 << 运算符正在另一个类中使用Histogram,其中包含。

任何帮助将不胜感激 :)

标签: c++vectorconstantsoperator-keywordostream

解决方案


在提供的代码中,您没有using namespace std在标头中使用“”,这是正确的,因此ostream没有定义(除非它以位为单位成为全局命名空间的成员,这将是不好的)并且编译器可能会处理两次出现ostream作为不同的类型,因此在 Histogram 类中声明的类型与您的 cpp 文件中friend operator<<的函数具有不同的类型。operator<<尝试使用std::ostream, 代替。

您还可以通过不复制operator<<使用中的向量或更好的 const 引用来改进代码:

const vector<float>& vals = hs.bucketValues;
const vector<float>& freq = hs.bucketFrequencies;

推荐阅读