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

Hol*_*lly 1 c++ oop header class

为了使用 OOP 进行一些练习,我正在尝试创建一个 Point 类(有 2 个整数、x 和 y)和一个 Line 类(有 2 个点)。

现在,当我去构建我的 main.cpp 时,我会收到类似的错误..

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

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

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

主程序

#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;
}
Run Code Online (Sandbox Code Playgroud)

行.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
Run Code Online (Sandbox Code Playgroud)

行.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 )) ) );
}
Run Code Online (Sandbox Code Playgroud)

点.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
Run Code Online (Sandbox Code Playgroud)

点.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;
}
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 6

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

有关如何执行此操作的确切说明取决于您使用的开发环境。