I can\'t for the life of me figure out why I am getting these errors, especially since I have include guards.
These are my errors (please ignore what I named my comp
As already stated in the comments, the << operator needs to be inlined or defined in the cpp file. When you define the function in the header file, it will be compiled in each cpp file where you include the header. If you include the header in more than one cpp file then you get the compiler errors because the same code will be compiled into multiple .obj files. The linker does not know which .obj file to use and throws an error.
Solution 1 - Splitting into .h and .cpp
loan.h
ostream & operator<<(ostream & ostr, Loan & aLoan);
loan.cpp
ostream & operator<<(ostream & ostr, Loan & aLoan) {
aLoan.printOn(ostr);
return ostr;
}
Solution 2 - Inlining
loan.h
inline ostream & operator<<(ostream & ostr, Loan & aLoan) {
aLoan.printOn(ostr);
return ostr;
}
The second solution will cause the compiler to resolve the function call by inlining the function code at every position in the code where an invocation happens. This causes redundancies in the compiled code and should be avoided for large functions.
Solution 3 - Static
loan.h
static ostream & operator<<(ostream & ostr, Loan & aLoan) {
aLoan.printOn(ostr);
return ostr;
}
By declaring the function as static, it has internal linkage. You are still leaving the decision of whether the compiler will inline it or not to the compiler.