C++错误:未找到成员声明
我是一个c++新手。今天,我遇到一个问题: 在头文件中,我定义了一个类:
template<class T> class Ptr_to_const {
private:
Array_Data<T>* ap;
unsigned sub;
public:
...
Ptr_to_const<T> & operator=(const Ptr_to_const<T> & p);
};
在源文件中,我编程为:
template<class T> Ptr_to_const<T>& Ptr_to_const<T>::operator=(
const Ptr_to_const<T> & p) {
...
return *this;
}
编译时,编译器总是说:“未找到成员声明”。 为什么?
我使用eclipse CDT+Cygwin GCC
非常感谢!
I am a c++ newbie. Today, I have a problem:
in header file, I define a class:
template<class T> class Ptr_to_const {
private:
Array_Data<T>* ap;
unsigned sub;
public:
...
Ptr_to_const<T> & operator=(const Ptr_to_const<T> & p);
};
and in source file, I program as:
template<class T> Ptr_to_const<T>& Ptr_to_const<T>::operator=(
const Ptr_to_const<T> & p) {
...
return *this;
}
when compiled, compiler always say: 'Member declaration not found'.
why?
I use eclipse CDT+Cygwin GCC
thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
模板类需要在标头或用户包含的另一个文件中声明和定义。它们不能像平常一样在标头中声明并在源文件中定义。
原因是模板必须替换为实际类型以及使用时生成和编译的源,并且编译器当然无法为可能出现的每种可能类型预编译模板,因此用户需要能够处理(因此,需要访问代码)。
如果多个库包含相同的模板,这确实会在传递对象时导致一些问题,因为它们可能针对不同版本的标头进行编译(请参阅“单一定义规则”)。
Template classes need to be both declared and defined in the header, or another file which is included by users. They can't be declared in a header and defined in a source file like usual.
The reasoning is that the template must be replaced with an actual type and the source for that generated and compiled when used, and the compiler certainly can't precompile templates for every possible type that may come along, so users need to be able to handle that (and so, need access to the code).
This does cause some issues when passing objects, if multiple libraries include the same templates, as they may be compiled against different versions of the header (see the One Definition Rule).
“未找到成员声明”是 Eclipse 静态分析工具 (codan) 产生的错误而不是编译器。如果出现此错误,但编译成功,则这是误报。众所周知,该工具的旧版本会产生一些误报,例如请参阅 此错误报告。因此我建议将 Eclipse CDT 更新到最新版本。如果这没有帮助,请向 Eclipse CDT 提交错误报告。
但是,如果您也从编译器中收到错误(这些错误由问题视图中类型列中的 C/C++ 问题指示),那么您可能忘记包含头文件。
"Member declaration not found" is an error produced by the Eclipse static analysis tool (codan) rather than compiler. If you get this error, but the compilation succeeds this is a false positive. Older versions of this tool are known to give some false positives, see for example this bug report. So I recommend updating Eclipse CDT to the most recent version. If this doesn't help, submit a bug report to Eclipse CDT.
However, if you get the errors from compiler too (these are indicated by C/C++ Problem in the Type column in the Problems view) then you have probably forgotten to include the header file.
您应该在头文件末尾包含源文件
或者在定义模板类时在头文件中定义成员函数
You should include your source file at the end of header file
or you define member function in header file when you define a template class