GustX
GustX

Reputation: 45

Overloading of Operators Unresolved External Error LNK1120,LNK2019

I have been trying to make a class of complex numbers work and just recently managed to make my 2 friend function definitions compile without errors Now I'm trying to test the overloaded operators by making 3 complex class objects in the (this is my main.cpp file)ExtraCredit.cpp file

    complex x(3.2);
    complex y(3.4, 4.1);
    complex z;

    z = x + y;

    cout << z;

The program worked up to z = x + y correctly but when I added

cout << z;

The output should be 6.2 + 4.1bi

But instead I get these 2 errors

LNK1120 1 unresolved externals 

LNK2019 unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> >&_cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char>>&,class complex)"(??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@Vcomplex@@@Z)referenced n function_main

In my ExtraCredit.cpp file I have

#include "stdafx.h" // This is VSO
#include <iostream>
#include "complex.h"

using namespace std;

in the top of complex.h

#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>

at the end of complex.h

#endif // COMPLEX_H

in the top of my complex.cpp file I have

#include "stdafx.h"
#include "complex.h"
#include <iostream>

using namespace std;

this is the overload prototype of the << operator in complex.h

friend std::ostream &operator<<(std::ostream &out, complex c);

this is the implementation/definition in complex.cpp

 std::ostream& operator<< (std::ostream& out, complex const& c) {
    return out << c.getReal() << "+" << c.getImag() << "i";
}

Upvotes: 0

Views: 1125

Answers (1)

Danh
Danh

Reputation: 6016

Your declaration is not the same with your definition:

friend std::ostream &operator<<(std::ostream &out, complex c);
std::ostream& operator<< (std::ostream& out, complex const& c) {
    return out << c.getReal() << "+" << c.getImag() << "i";
}

You need to change your declaration to

friend std::ostream &operator<<(std::ostream &out, const complex &c);

Upvotes: 1

Related Questions