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

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

问题描述

我是一位尝试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天全站免登陆