对具有相同参数的成员函数的未定义引用

Undefined reference to member function with identical parameters

本文关键字:成员 函数 未定义 引用 参数      更新时间:2023-10-16

在头文件"asteroid.h"中,我有结构体"Asteroid"。在结构中,我声明以下函数。

bool isCollidingWith (Asteroid a2);

在 cpp 文件"小行星.cpp"中,我有以下代码

bool Asteroid::isCollidingWith (Asteroid a2)
{
    return true;
}

程序给了我错误

未定义对"Asteroid::isCollidingWith(Asteroid)"的引用

我尝试从.cpp中删除"小行星::",但无济于事。在另一个.cpp中,主文件(collision.cpp,我无法编辑),称为"isCollidingWith"

if (a1.isCollidingWith(a2))

上面的行是我的程序查明错误的地方。 碰撞.cpp #include"asteroid.h",但不是小行星.cpp。在小行星.cpp中,我#include asteroid.h,所以我认为我的内含物没有错误。我在网上查看了"未定义引用"错误的常见原因,这通常是由于 .h 文件和 .cpp 文件中的参数不同,但我的参数是相同的。有谁知道我能做些什么来解决这个问题?

编辑:小行星CPP的代码

#include "asteroid.h"
#include "point.h"
#include "line.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
new Asteroid asteroid1;
cout << "Program is running";
new Asteroid asteroid2;
string Asteroid::getInput (Asteroid a)
{
    cout << "whats the amount of vertices"
    double input;
    getline(cin, input);
    a.amountofpoints = input;
    input;
    double xinput;
    double yinput;
    cout << "input two numbers for the x and y of each vertice"
    while (input > 0)
    {
        getline(cin, input2);
        getline(cin, input3);
        a.vertice[input].x = input2;
        a.vertice[input].y = input3;
        input--;
    }
}
bool Asteroid::isCollidingWith (Asteroid a2) const
{
    //might need to take in Asteroid a2 to see if they're equal, not sure
    return true;
}
Point Asteroid::getCenter() const
{
    return a1;
}
double Asteroid::moveBy(double deltx, double delty) const
{
    return deltx;
    return delty;
}
void Asteroid::print() const
{
    cout << "Print Function" << endl;
    return a1;
}
Point Asteroid::addVertex(Point newvertex) const
{
    return newvertex;
}

小行星代码.h

#ifndef ASTEROID_H_INCLUDED
#define ASTEROID_H_INCLUDED
#include <iostream>
#include <string>
#include "point.h"
#include "line.h"
using namespace std;
struct Asteroid
{
    int amountofpoints;
    Point vertice;
    /**
    Create a line signment iwth the given endpoints.
    */
    bool isCollidingWith (Asteroid a2) const;
    Point getCenter () const;
    string getInput (Asteroid a);
    double moveBy (double deltx, double delty);
    std::ostream& print(std::ostream &out);
    Point addVertex(Point newvertex);
    //bool isCollidingWith;
};
#endif

我意识到我在 cpp 中的函数的"内部"基本上是空的;现在,我试图让程序编译,以便我可以一次处理一个函数,但错误阻止了我。下面是生成消息。

C:\Users\jclary\Desktop\adt_asteroids2\collision.cpp|44|未定义引用 'Asteroid::isCollidingWith(Asteroid) const'|

链接器必须查看所有源文件 (*.cpp) 才能制作可执行文件。因此,您必须以某种方式将所有文件名提供给链接器。究竟是怎么回事?这取决于您的平台。

如果您使用的是 gcc:

g++ asteroid.cpp collision.cpp -o whatever

如果您使用的是 MS Visual Studio:

将文件拖放到asteroid.cppcollision.cpp和所有头文件到"项目"或"解决方案"或任何名称上。

如果您使用其他系统,请在您的问题中指定它,熟悉它的人将为您提供帮助。