链接时为什么会出现未定义的符号?

sim*_*dam -1 c++ linker-errors ld

我有两个类Triangle,ALine我想在其构造函数中ALine为属性分配新实例Triangle.但是我收到了这个错误

Undefined symbols for architecture x86_64:
  "ALine::ALine()", referenced from:
      Triangle::Triangle(triangle) in Triangle.o
ld: symbol(s) not found for architecture x86_64
Run Code Online (Sandbox Code Playgroud)

以下是我写的代码:

ALine.cpp

#include "Geometry.h"
#include "ALine.h"



ALine::ALine(point a, point b)
{       
        double tmpy = a.y - b.y;
        double tmpx = a.x - b.x;
        double tmpk;
        if(equals(tmpy, 0))
        {
            tmpk = 0;
        }
        else
        {
            tmpk = tmpx/tmpy;
        }
        double tmpq = a.y - tmpk*a.x;
        if(equals(tmpx, 0))
        {
            if(equals(a.x, 0))
            {
                if(equals(b.x, 0)) tmpk = 0;
                else tmpk = (b.y-tmpq)/b.x;
            }
            else
            {
                tmpk = (a.y-tmpq)/a.x;
            }
        }



        a = a;
        b = b;
        k = tmpk;
        q = tmpq;

};
Run Code Online (Sandbox Code Playgroud)

ALine.h

class ALine{

private:
    double k;
    double q;
    point a;
    point b;

    double length;

    void calculateLength();

public:

    ALine(point a, point b);
    ALine();



    point getK();
    point getQ();


    static bool areinline(point a, point b, point c);


};
Run Code Online (Sandbox Code Playgroud)

Triangle.cpp

#include "Triangle.h"
#include "Geometry.h"
#include "ALine.h"





    Triangle::Triangle(triangle t)
    {
        triangle itself = t;
        a = *new ALine(itself.a, itself.b);
        b = *new ALine(itself.b, itself.a);
        c = *new ALine(itself.c, itself.a);
    };
Run Code Online (Sandbox Code Playgroud)

注意,这些类不完整,我在这里只粘贴相关代码到我的问题(如果没有,我可以添加更多).

Wug*_*Wug 6

您正在声明默认构造函数但未定义构造函数.

// in ALine.h
class ALine
{
private:
    void calculateLength(); // this is a declaration
public:
    ALine(point a, point b); // this is another
    ALine(); // this is a declaration as well

...

// in ALine.cpp
ALine::ALine(point a, point b) // this is a definition
{
    double tmpy = a.y - b.y;
    double tmpx = a.x - b.x;
    double tmpk;
    ...
Run Code Online (Sandbox Code Playgroud)

你告诉编译器函数存在,所以它让你使用它.这是合法的.但是,当链接器尝试处理已编译的代码时,它会查找ALine::ALine()并找不到它,因为您从未说过它是什么.

添加到您的ALine.cpp,如下所示:

ALine::ALine()
{
}
Run Code Online (Sandbox Code Playgroud)

话虽如此

您没有正确使用动态分配.就像现在一样,你在堆上分配一个新的ALine,将它复制到堆栈的ALine中,然后丢弃堆ALine的地址(不是一次,而是3次).这是一个内存泄漏,ALines永远不会消失,只要你的程序运行,它们将永远存在.

更改Triangle::Triangle(triangle other)为以下内容会更好:

Triangle::Triangle(const triangle& t) : a(t.a, t.b), b(t.b, t.c), c(t.c, t.a) {}
Run Code Online (Sandbox Code Playgroud)

这使用语法Class::Class(args ...) : member(...), member2(...), ... { /* body */ }来初始化构造函数中的类的成员.这样做的一个好处是它们的默认构造函数不会被调用,因为它们会(隐式地)在您的代码中.