Qt:未定义对的引用

Qt: Undefined reference to

本文关键字:引用 未定义 Qt      更新时间:2023-10-16

刚开始使用Qt时遇到一个错误,不知道是否有人能澄清这个问题。在谷歌上搜索并查看类似的问题,但似乎无法找到解决方案;

C:UsersSebDesktopSDIcw2main.cpp:10: error: undefined reference to `SDI::shipHandler::shipHandler(SDI::shipHandler&)'

出现在我的main.cpp中的第10行"w.populateCombo(shipHandler(;";

#include "widget.h"
#include <QApplication>
#include "shipHandler.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    SDI::shipHandler shipHandler("ships/ships.txt");
    w.populateCombo(shipHandler);
    return a.exec();
}

shipHandler.cpp(构造函数和析构函数(

SDI::shipHandler::shipHandler(std::string fileName)
{
    shipCount = 0;
    std::string line;
    std::ifstream infile;
    infile.open(fileName.c_str());
    while(!infile.eof()) 
    {
        getline(infile,line); 
        shipHandler::lineParse(line);
        shipCount++;
    }
    infile.close();
}
SDI::shipHandler::~shipHandler()
{
}

shipHandler.h

#ifndef SDI__shipHandler
#define SDI__shipHandler
#include "common.h"
#include "navalVessels.h"
namespace SDI
{
    class shipHandler
    {
        //variables
    public:
        std::vector<SDI::navalVessels*> ships;
        int shipCount;
    private:
        //function
    public:
        shipHandler();
        shipHandler(std::string fileName);
        shipHandler(SDI::shipHandler& tbhCopied);
        ~shipHandler();
        void lineParse(std::string str);
        void construct(std::vector<std::string> line);
        std::vector<int> returnDates(std::string dates);
    private:
    };
}
#endif

如有任何帮助,我们将不胜感激。

刚读到错误消息,它似乎正在尝试使用复制构造函数(shipHandler(SDI::shipHandler& tbhCopied)(,但您从未在shipHandler.cpp.中完全定义过它

class shipHandler
{
    // ...
public:
    shipHandler(); // this isn't defined anywhere
    shipHandler(std::string fileName);
    shipHandler(SDI::shipHandler& tbhCopied); // this isn't defined anywhere
    ~shipHandler();
    // ...
};

首先,您应该停止声明复制构造函数,或者完成对它的定义:

// in shipHandler.cpp
SDI::shipHandler::shipHandler(SDI::shipHandler& tbhCopied) {
    // fill this in
}

您还应该定义或删除默认构造函数(SDI::shipHandler::shipHandler()(。

接下来,您可能可以将shipHandler作为参考而不是创建副本:

// most likely, this is what you want
void Widget::populateCombo(const shipHandler& handler);
// or maybe this
void Widget::populateCombo(shipHandler& handler);

这些可能是有用的参考:

定义和声明之间有什么区别?

c++通过引用和指针传递参数