对我的类的未定义引用?C++初学者

Undefined reference to my classes? C++ Beginner

本文关键字:C++ 初学者 引用 未定义 我的      更新时间:2023-10-16

为了练习OOP,我尝试创建一个Point类(有2个int,x&y)和Line类(有两个Points)。

现在,当我去构建我的main.cpp时,我会遇到这样的错误。。

"对`Point::Point(float,float)'的未定义引用"

"对`Line::Line(Point,Point)'的未定义引用"

不知道为什么,也许你可以简单地看一下我的文件?非常感谢!

Main.cpp

#include "Point.hpp"
#include "Line.hpp"
#include <iostream>
using namespace std;
int main()
{
    Point p1(2.0f, 8.0f); // should default to (0, 0) as specified
    Point p2(4.0f, 10.0f);  // should override default
    p1.setX(17);

    if ( p1.atOrigin() && p2.atOrigin() )
        cout << "Both points are at origin!" << endl;
    else
    {
        cout << "p1 = ( " << p1.getX() << " , " << p1.getY() << " )" <<endl;
        cout << "p2 = ( " << p2.getX() << " , " << p2.getY() << " )" <<endl;
    }
    Line line(p1, p2);
    Point midpoint = line.midpoint();
    cout << "p1 = ( " << midpoint.getX() << " , " << midpoint.getY() << " )" <<endl;
    return 0;
}

线路.hpp

#ifndef _LINE_HPP_
#define _LINE_HPP_
#include "Point.hpp"
class Line{
public:
    Line(Point p1, Point p2);
    //void setp1(Point p1);
    //void setp2(Point p2);
    //Point getp1 finish
    Point midpoint();
    int length();
private:
    int _length;
    Point _midpoint;
    Point _p1, _p2;
};
#endif

Line.cpp

#include "Line.hpp"
#include <math.h>
Line::Line(Point p1, Point p2) : _p1(p1), _p2(p2)
{
}
Point Line::midpoint()
{
    _midpoint.setX() = (_p1.getX()+ _p2.getX()) /2;
    _midpoint.setY() = (_p1.getY()+ _p2.getY()) /2;
}
int Line::length()
{
    //a^2 + b^2 = c^2
    _length = sqrt( ( (pow( _p2.getX() - _p1.getX(), 2 ))
                     +(pow( _p2.getY() - _p1.getY(), 2 )) ) );
}

点.hpp

#ifndef _POINT_HPP_
#define _POINT_HPP_
class Point {
public:
    Point( float x = 0, float y = 0);
    float getX() const;
    float getY() const;
    void setX(float x = 0);
    void setY(float y = 0);
    void setXY(float x = 0, float y = 0);
    bool atOrigin() const;
private:
    float _x, _y;
};
#endif

Point.cpp

#include "Point.hpp"
Point::Point(float x, float y) : _x(x), _y(y)
{
}
float Point::getX() const
{
    return _x;
}
float Point::getY() const
{
    return _y;
}
void Point::setX(float x)
{
    //if (x >= 0 &&
    _x = x;
}
void Point::setY(float y)
{
    //might want to check
    _y = y;
}
void Point::setXY(float x , float y )
{
    setX(x);
    setY(y);
}
bool Point::atOrigin() const
{
    if ( _x == 0 && _y == 0)
        return true;
    return false;
}

在C++中,不仅要编译main.cpp,还要编译Line.cppPoint.cpp文件。然后,当您将它们全部编译为对象文件时,必须对象文件链接在一起。这是由一些其他语言(如Java)自动处理的。

关于如何做到这一点的确切说明将取决于您使用的开发环境。

您的Point.cpp没有被编译或提供给链接器,请尝试将其包含在您的构建中。