【问题标题】:std::vector inaccessibility with const onjectstd::vector 无法访问 const 对象
【发布时间】:2021-02-26 17:08:42
【问题描述】:

我试图重载直方图类的

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

但是,bucketValuesbucketFrequencies 无法从此 const 对象访问,hs。我该如何解决这个问题?
我需要函数参数有一个 const,因为这个 Histogram。

任何帮助将不胜感激:)

【问题讨论】:

  • 标记你的getter方法const然后使用那些?
  • 你能张贴准确的逐字错误信息吗?你在输出操作符中叫什么truncFn()?这似乎是错误的(无论这个函数应该做什么),这是编译器抱怨的唯一部分。
  • hs.truncfn —> Histogram::truncfn.
  • 我看不出有什么问题,我已经测试了你的代码,它使用 C++11 编译得很好
  • @TigerYu 奇怪!当时它说我无法到达

标签: c++ vector constants operator-keyword ostream


【解决方案1】:

在提供的代码中,您没有在标头中使用“using namespace std”,这是正确的,因此未定义 ostream(除非它以位为单位成为全局命名空间的成员,否则会很糟糕)并且编译器可能会将两次出现的ostream 视为不同的类型,因此在直方图类中声明的friend operator&lt;&lt; 具有与cpp 文件中的函数operator&lt;&lt; 不同的类型。尝试改用std::ostream

您还可以通过不复制 operator&lt;&lt; 中的向量来改进代码 - 使用引用,或者更好的 const 引用:

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

【讨论】:

  • 你是对的!我忘记了 using namespace std :) const 引用是个好主意,非常感谢 :)
猜你喜欢
  • 2014-10-28
  • 2011-05-06
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
相关资源
最近更新 更多