运算符重载未解决的外部错误LNK1120,LNK2019

时间:2015-12-12 02:25:55

标签: c++

我一直试图让一类复杂的数字起作用,并且最近设法使我的2个朋友的函数定义编译没有错误 现在我试图通过在(这是我的main.cpp文件)ExtraCredit.cpp文件中创建3个复杂的类对象来测试重载的运算符

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

    z = x + y;

    cout << z;

该程序正确地工作到z = x + y但是当我添加

cout << z;

输出应为6.2 + 4.1bi

但我得到了这两个错误

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

在我的ExtraCredit.cpp文件中,我有

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

using namespace std;

位于complex.h的顶部

#ifndef COMPLEX_H
#define COMPLEX_H

#include <iostream>

在complex.h的末尾。

#endif // COMPLEX_H

在我的complex.cpp文件的顶部我有

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

using namespace std;

这是&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; complex.h中的运算符

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

这是complex.cpp

中的实现/定义
 std::ostream& operator<< (std::ostream& out, complex const& c) {
    return out << c.getReal() << "+" << c.getImag() << "i";
}

1 个答案:

答案 0 :(得分:1)

您的声明与您的定义不同:

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";
}

您需要将声明更改为

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