c++ - 运算符重载 Unresolved external 错误 LNK1120、LNK2019

标签 c++

我一直在尝试让一类复数工作并且最近才成功地让我的 2 个 friend 函数定义编译没有错误 现在我试图通过在(这是我的 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;

这是complex.h中<<运算符的重载原型(prototype)

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

关于c++ - 运算符重载 Unresolved external 错误 LNK1120、LNK2019,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34235553/

相关文章:

.net - 如何将 boost::asio 套接字转换为 C++/CLI .Net 套接字?

c++ - 使用 gcc 版本 4.1.2 模拟 is_pointer

c++ - 在 Xcode 中使用 C++17 标准库中的贝塞尔数学函数

c++ - 使用 CMake 构建 GStreamer 会导致 SDP 和 WebRTC 无法解析的外部符号错误

c++ - 如何自动对 QTreeWidget 列进行排序?

两个 unordered_set 交集的 C++ 库方法

c++ - 使用输入字符串作为变量名

内部命名空间的 C++ 命名空间解析

c++ - 是否有一种 STL 方法可以对指针 vector 进行深度复制?

c++ - 通过模板或纯虚拟基类继承进行动态类型文件访问?