对我的类的未定义引用?C++初学者
Undefined reference to my classes? C++ Beginner
为了练习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.cpp
和Point.cpp
文件。然后,当您将它们全部编译为对象文件时,必须将对象文件链接在一起。这是由一些其他语言(如Java)自动处理的。
关于如何做到这一点的确切说明将取决于您使用的开发环境。
您的Point.cpp没有被编译或提供给链接器,请尝试将其包含在您的构建中。
相关文章:
- C++错误消息*成员参考.**初学者*
- 嵌套for循环C++的问题(初学者)
- 我是 C++ 的初学者,我想知道如何在 2D 矢量中获取重复值
- 初学者如何使用标准::any_of?
- 初学者问题:如何使用这些晦涩难懂的命令,例如C++中的'RenderWindow'
- C++初学者:为什么我的编译器根据我的循环返回"name not found"?
- 初学者问题:如何访问此变量?
- 您好,我是C++初学者,有这种问题.它给了我倍增的错误
- 图形初学者C++(跳过控制台)?
- 我是初学者,无法理解c ++程序中的以下错误
- 试图美化这个Arduino代码[初学者在这里]
- 初学者问题:C++指针/地址 - 和变量之后不是以前?
- 初学者关于数组和指针的问题
- 如何修复初学者C++代码中发生的未定义行为
- 如何从字符数组C++中提取2个整数并将它们存储在2个变量中(初学者)
- 初学者C++线程安全单例设计
- 初学者:在向量中降低
- 模板编程初学者问题
- C ++初学者使用while循环生成随机数
- 在 Rcpp-Function 中使用布尔向量的子集(Rcpp 初学者的问题..)