类模板友元函数的声明(友元函数可以在类内定义吗)

2009-08-09摘自《SunStudio12:C++用户指南》第6.7.3节 模板在使用前必须先声明。一个友元声明构成了模板的使用,而非模板的声明。(Afrienddeclarationconstitutesauseofthetemplate,notadeclarationofthetemplate.)所以实际的模板声明必须在友元声明之前

大家好,又见面了,我是你们的朋友全栈君。

2009-08-09

摘自《Sun Studio 12: C++ 用户指南》 第 6.7.3 节

 

模板在使用前必须先声明。一个友元声明构成了模板的使用,而非模板的声明。(A friend declaration constitutes a use of the template, not a declaration of the template. )所以实际的模板声明必须在友元声明之前。例如,编译系统尝试链接以下示例中生成的目标文件时,对未实例化的operator<<函数,会生成一个未定义的错误

 

示例6–2 友元声明问题的示例

 

请注意,因为编译器将以下代码作为普通函数(array类的friend)的声明进行读取(because the compiler reads the following as the declaration of a normal function that is a friend of the array class),所以编译期间不会出现错误消息

因为operator<<实际上是模板函数,所以需要在声明template class array之前提供此“模板函数”(operator<<?)的声明。但是,由于operator<<有一个type为array<T>的形参(模板类型形参?),因此在声明函数之前,必须声明array<T>。文件array.h必须如下所示:

Because operator<< is really a template function, you need to supply a template declaration for prior to the declaration of template class array. However, because operator<< has a parameter of type array<T>, you must precede the function declaration with a declaration of array<T>. The file array.h must look like this:

 

 //———————————————————————————–

换一个能通过的版本,所有代码都放到同一个文件中。前面那个未通过乃是因为文件之间include有问题,在array.cc中#include “array.h”,然后在main.cc中#include “array.cc”即可。

//———————————————————————————— 

再换一个所有代码合在一起的版本,使用了using namespace std;

主要是验证下面这段代码的第七行

“template<class T> ostream& operator<<(ostream&, const array<T>&);”

可以被删掉!

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/127793.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号