操作员过载未解决的外部错误LNK1120、LNK2019

Overloading of Operators Unresolved External Error LNK1120,LNK2019

本文关键字:错误 LNK1120 LNK2019 外部 未解决 操作员      更新时间:2023-10-16

我一直在尝试使一类复数工作,最近才成功地使我的两个朋友函数定义编译无误现在,我试图通过在(这是我的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

但相反,我得到了这2个错误

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;

在复合体顶部.h

#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>

在复合体的末端。h

#endif // COMPLEX_H

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

#include "stdafx.h"
#include "complex.h"
#include <iostream>
using namespace std;

这是<lt;复杂.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";
}

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

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);