链接CPP文件进行测试时出现LNK2019错误

时间:2019-11-01 17:26:10

标签: c++ lnk2019

我正在尝试编写一个对三次多项式执行运算的Cubic类,当尝试重载+运算符以返回新的Cubic对象时,它给了我LNK2019错误:

在函数“ public:class Cubic const __thiscall Cubic :: operator +(cubic class)”中引用的“未解析的外部符号“ public:__ thiscall Cubic :: Cubic(void)”(?? 0Cubic @@ QAE @ XZ))? ?HCubic @@ QAE?BV0 @ V0 @@ Z)“

我试图查看我的函数声明是否不同于我的定义,但是它们都相同。我相信问题出在重载运算符上,因为我尝试使用rhs.coefficient[i] += coefficient[i]修改每个系数并返回rhs,但效果很好。我之所以要返回一个新的Cubic,是因为它看起来更正确,而且还可以更轻松地实现-运算符。

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

Cubic.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;
}

Test.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

1 个答案:

答案 0 :(得分:1)

您的问题是您为Cubic类的默认构造函数 声明了 ,这里:

// Default constructor
Cubic();

但是您从未 定义 该构造函数(至少在您显示的任何代码中都没有)。

您需要定义默认构造函数内联,如下所示:

// 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.