爲了通過OOP獲得一些練習,我嘗試創建一個Point類(有2個整數,x & y)和一個Line類(有2個點)。未定義的對我的類的引用? C++初學者
現在,當我去建立我的main.cpp我得到這樣的錯誤..
「未定義參考`點::點(浮動,浮動)」 「和
」 未定義參考'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;
}
Line.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))));
}
Point.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;
}
你是否將所有cpp文件包含在編譯中? – 2012-01-13 21:15:28
你鏈接了所有的文件嗎?你的編譯和鏈接命令行是什麼? – jpalecek 2012-01-13 21:15:35
啊我現在看到問題了。我正在使用codeblocks IDE,但到目前爲止我只是點擊綠色的小綠色按鈕來編譯和運行單個文件:p我很確定我可以找出如何使用命令行鏈接或將所有文件放入codeblock項目可以工作。謝謝 – Holly 2012-01-13 21:20:35