对构造函数的未定义引用 [英] Undefined reference to constructor

查看:31
本文介绍了对构造函数的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名尝试 C++ 的 Java 开发人员.

I'm a Java developer experimenting with C++.

我刚刚创建了一个新课程.在我的其他课程中,我想要列出可以存储过滤器对象的列表.

I just created a new class. In my other class I want to have list where I can store Filter objects.

Filter.h

#ifndef FILTER_H_
#define FILTER_H_

class Filter {
public:
  Filter(int id);
  int id;
  ~Filter();

};

#endif /* FILTER_H_ */

Filter.cpp

#include "Filter.h"

Filter::Filter(int id) {
this.id = id;
}
Filter::~Filter() {
}

Cars.h

#include "Filter.h"
...
...
private:
  std::vector<Filter> filters;

Cars.cpp

所以在这里的一个函数中我尝试这样做:

so in a function here I try to do this:

int id = 2;
Filter *filter = new Filter(id);

产生此错误:

Cars.cpp:120: undefined reference to `Filter::Filter(int)'
stl_construct.h:83: undefined reference to `Filter::~Filter()'

这是什么原因?

推荐答案

这个错误是链接器产生的,因为它看不到构造函数的定义在哪里.

The error is generated by the linker because it can not see where the definition of the constructor is located.

如果您使用的是 IDE,则应将两个 .cpp 文件添加到项目中,以便它们可以一起编译,并且链接器可以找到定义.不是,那么您必须自己组合它们 - 假设您使用的是 gcc:

If you are using an IDE, you should add both .cpp files to the project so that they can be compiled together and the definition would be found by the linker. It not, then you have to combine them yourself -assuming you are using gcc:

g++ cars.cpp filter.cpp

会将它们组合成一个可执行文件,并且不应该向您显示那个错误

will combine them into one executable and should not show you that error

这篇关于对构造函数的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆