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

问题描述 投票:0回答:1

[我正在尝试编写一个对三次多项式执行运算的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的原因是因为它看起来更正确,而且还因为它使实现-运算符更加容易。

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

c++ lnk2019
1个回答
0
投票

您的问题是您为Cubic类具有默认的构造函数declared,在这里:

// Default constructor
Cubic();

但是您从来没有defined那个构造函数(至少,没有在您显示的任何代码中)。

您需要define默认构造函数inline,如下所示:

// Default constructor
Cubic() { } // This provides a definition, but it doesn't DO anything.

或在其他地方提供单独的定义:

Cubic::Cubic()
{
    // Do something here...
}

您还可以将“ Do something”代码添加到inline定义中!如果定义较小(一两行),大多数编码器会执行此操作,但是对于更复杂的代码,请分开定义。

© www.soinside.com 2019 - 2024. All rights reserved.