Given this code sample:
complex.h :
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
class Complex
{
public:
Complex(float Real, float Imaginary);
float real() const { return m_Real; };
private:
friend std::ostream& operator<<(std::ostream& o, const Complex& Cplx);
float m_Real;
float m_Imaginary;
};
std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}
#endif // COMPLEX_H
complex.cpp :
#include "complex.h"
Complex::Complex(float Real, float Imaginary) {
m_Real = Real;
m_Imaginary = Imaginary;
}
main.cpp :
#include "complex.h"
#include <iostream>
int main()
{
Complex Foo(3.4, 4.5);
std::cout << Foo << "\n";
return 0;
}
When compiling this code, I get the following error:
multiple definition of operator<<(std::ostream&, Complex const&)
I've found that making this function inline
solves the problem, but I don't understand why. Why does the compiler complain about multiple definition? My header file is guarded (with #define COMPLEX_H
).
And, if complaining about the operator<<
function, why not complain about the public real()
function, which is defined in the header as well?
And is there another solution besides using the inline
keyword?
static
for this purpose is deprecated in C++.static
has been completely replaced by anonymous namespaces, although in this particular case,inline
is the way to go. – Konrad Rudolphoperator<<
) different meanings in different translation units. – Davis Herring