我一直在尝试让一类复数工作并且最近才成功地让我的 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/