1

I'm trying to use separate files for my project, including header file, which declares class methods and .cpp file for defining methods.

But, enforcing hidden method implementation I get errors and can't compile code.

File vector.h

#ifndef VECTOR_H
#define VECTOR_H


#include <iostream>

class Point
{
private:
    float x;
    float y;

public:
    Point(float x, float y);
    float get_x() const;
    float get_y() const;

};

#endif // VECTOR_H

File vector.cpp

#include "vector.h"

Point::Point(float x, float y): x(x), y(y) {}

float Point::get_x() const
{
    return x;
}

float Point::get_y() const
{
    return y;
}

Point operator+(Point& pt1, Point& pt2)
{
    return {pt1.get_x() + pt2.get_x(), pt1.get_y() + pt2.get_y()};
}

std::ostream& operator<<(std::ostream& os, const Point& pt)
{
    os << '(' << pt.get_x() << ', ' << pt.get_y() << ')';
    return os;
}

File source.cpp

#include "vector.h"

int main()
{
    Point p1(1.4, 2.324), p2(2.004, -4.2345);

    std::cout << p1 << '\n';
    std::cout << p2 << '\n';
    std::cout << p1 + p2 << '\n';

    return 0;
}

In the end I get:

error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'Point')

error: no match for 'operator+' (operand types are 'Point' and 'Point')
Axiumin_
  • 1,932
  • 2
  • 15
  • 22
Pr.Germux
  • 55
  • 5

1 Answers1

3

You have a compile error for your main knows nothing about operator+ and operator<<.

Write

Point operator+(Point& pt1, Point& pt2);
std::ostream& operator<<(std::ostream& os, const Point& pt);

in h file or forward declare them in the main file.

One more thing. You should use "" in << ", " <<.

CoralK
  • 3,341
  • 2
  • 9
  • 22
Nestor
  • 637
  • 5
  • 12