c++ - 链接 CPP 文件进行测试时出现 LNK2019 错误
问题描述
我正在尝试编写一个对 3 次多项式执行运算的 Cubic 类。当尝试重载 + 运算符以返回一个新的 Cubic 对象时,它给了我一个 LNK2019 错误:
“未解析的外部符号“public: __thiscall Cubic::Cubic(void)” (??0Cubic@@QAE@XZ) 在函数“public: class Cubic const __thiscall Cubic::operator+(class Cubic)” (??HCubic@ @QAE?BV0@V0@@Z)"
我试过查看我的函数声明是否与我的定义不同,但它们都是一样的。我相信问题出在重载的运算符上,因为我尝试使用rhs.coefficient[i] += coefficient[i]
并返回 rhs 来修改每个系数,并且效果很好。我想返回一个新的 Cubic 的原因是因为它看起来更正确,也因为它也可以更容易地实现 - 运算符。
立方.h 文件
#include <iostream>
using namespace std;
class Cubic
{
public:
// Default constructor
Cubic();
// Predetermined constructor
Cubic(int degree3, int degree2, int degree1, int degree0);
// Return coefficient
int getCoefficient(int degree) const;
// Addition op
const Cubic operator+(Cubic rhs);
// Output operators
friend ostream& operator<<(ostream& outStream, const Cubic& cubic);
private:
int coefficient[4];
};
立方.cpp
#include "Cubic.h"
#include <iostream>
using namespace std;
Cubic::Cubic(int degree3, int degree2, int degree1, int degree0)
{
coefficient[3] = degree3;
coefficient[2] = degree2;
coefficient[1] = degree1;
coefficient[0] = degree0;
}
int Cubic::getCoefficient(int degree) const
{
return coefficient[degree];
}
const Cubic Cubic::operator+(Cubic rhs)
{
Cubic result;
for (int i = 3; i >= 0; i--)
{
result.coefficient[i] = coefficient[i] + rhs.coefficient[i];
}
return result;
}
ostream& operator<<(ostream& outStream, const Cubic& cubic) {
outStream << showpos << cubic.getCoefficient(3) << "x^(3)"
<< cubic.getCoefficient(2) << "x^(2)"
<< cubic.getCoefficient(1) << "x"
<< cubic.getCoefficient(0);
return outStream;
}
测试.cpp
#include "Cubic.h"
#include <iostream>
using namespace std;
int main()
{
Cubic lhs(3, 1, -4, -1);
Cubic rhs(-1, 7, -2, 3);
/* TESTS */
cout << "Addition using + operator" << endl;
cout << lhs + rhs << endl;
return 0;
}
预期的结果应该是+2x^(3)+8x^(2)-6x+2
。
解决方案
你的问题是你已经为你的类声明了一个默认构造函数Cubic
,在这里:
// Default constructor
Cubic();
但是您从未定义过该构造函数(至少,在您显示的任何代码中都没有)。
您需要定义默认构造函数inline,如下所示:
// Default constructor
Cubic() { } // This provides a definition, but it doesn't DO anything.
或在其他地方提供单独的定义:
Cubic::Cubic()
{
// Do something here...
}
您还可以将“做某事”代码添加到内联定义中!如果定义很小(一两行),大多数编码人员会这样做,但对于更复杂的代码,将定义分开。
编辑:或者,正如@Scheff 在评论中指出的那样,您可以使用以下方法显式定义默认构造函数:
// Default constructor
Cubic() = default; // Will do minimal required construction code.
推荐阅读
- android - android中的layout和viewGroup有什么区别
- powershell - 无法在 Windows 10 上将 OCaml 添加到系统路径
- c# - 我遇到了 ef-code first sql 的问题
- ios - Ionic 5.4 - 在离线模式下剪切音轨
- postgresql - Aurora Postgress 与 Aurora Mysql 中的字符串 JSON 文档
- c# - 我无法在 VS 2019 中添加引用
- c++ - push_back vector的Iterator时不使用构造函数是否安全
向量? - flutter - 如何在后台连续运行颤振应用程序?
- javascript - 我尝试使用 vue-resource 并得到“未捕获的类型错误:window.Vue.use 不是函数”
- rabbitmq - 等待 10000 毫秒后,用于通道的 Rabbitmq 消费者调度程序未关闭