C++ 对构造函数的未定义引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11792224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:33:22  来源:igfitidea点击:

Undefined reference to constructor

c++g++

提问by Ole-M

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

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

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

我刚刚创建了一个新类。在我的另一个班级中,我想列出可以存储 Filter 对象的列表。

Filter.h

过滤器.h

#ifndef FILTER_H_
#define FILTER_H_

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

};

#endif /* FILTER_H_ */

Filter.cpp

过滤器.cpp

#include "Filter.h"

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

Cars.h

汽车.h

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

Cars.cpp

汽车.cpp

so in a function here I try to do this:

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

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

which generate this error:

产生这个错误:

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

What's the reason for this?

这是什么原因?

回答by Lyubomir Vasilev

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

错误是由链接器产生的,因为它看不到构造函数的定义所在的位置。

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:

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

g++ cars.cpp filter.cpp

will combine them into one executable and should not show you thaterror

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