Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

c++ - "<<" Operator overloading error when defined outside main file

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

main() has no idea about your operator<< because you did not declare it in data.hpp in a scope where main() can find it. It needs to be declared as a free-floating function, not as a friend of the Data class, eg:

#ifndef DATA_H
#define DATA_H

#include <ostream>
#include <vector>

struct Point {
    double x;
    double y;
};

std::ostream& operator<<(std::ostream& out, const Point& point); // <-- moved here

class Data {
    public:
        Data (unsigned int);
        unsigned int n_samples;
        std::vector<Point> get();

    private:
        std::vector<Point> data;
};

#endif /* DATA_H */

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...