I tried to overload the << operator and wanted to use it in the main function. However, I get the following compiler error:
main.cpp:14:19: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘const Point’)
std::cout << point;
~~~~~~~~~~^~~~~~~~
Interestingly, if I put all the code into a single file, it works just fine.
The code looks as follows:
main.cpp
#include <vector>
#include <iostream>
#include "data.hpp"
int main() {
const unsigned int n_points = 10;
Data data (n_points);
std::vector<Point> d;
d = data.get();
for (const auto& point : d){
std::cout << point;
}
return 0;
}
data.cpp
#include <cmath>
#include <algorithm>
#include "data.hpp"
Data::Data (unsigned int _n_samples) {
n_samples = _n_samples;
data.resize(n_samples, {4.0, 2.0});
}
std::vector<Point> Data::get(){
return data;
}
std::ostream& operator<<(std::ostream& out, const Point& point){
out << point.x << " " << point.y << '
';
return out;
}
data.hpp
#ifndef DATA_H
#define DATA_H
#include <ostream>
#include <vector>
struct Point {
double x;
double y;
};
class Data {
public:
Data (unsigned int);
unsigned int n_samples;
std::vector<Point> get();
friend std::ostream& operator<<(std::ostream& out, const Point& point);
private:
std::vector<Point> data;
};
#endif /* DATA_H */
Can someone please tell me why this error occurs?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…