c++ - 带有 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
,其中包含。
任何帮助将不胜感激 :)
解决方案
在提供的代码中,您没有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;
推荐阅读
- ssl - 如何安全关闭 SSL 连接
- java-8 - Java 应用程序中的服务器事件有哪些选项?
- java - 转换数据集时出现 RuntimeException
到 JavaRDD
然后是数据框
- autodesk-forge - 自定义 BIM360 查看器?
- javascript - 使用 JS 为我的客户创建浏览器扩展程序或其他脚本
- dataset - 在主题独立的 10 倍交叉验证中训练、验证和测试中的数据拆分?
- python - 我是否必须将 matplotlib 与 Python 3 分开安装?
- python - URL重定向不适用于请求,Python
- jenkins-job-dsl - 如何在同一配置块中附加到由 Jenkins 作业 dsl 创建的节点?
- ruby - Ruby 编码 - 替换无效编码?