类模板的友元函数(转载)

from:

http://topic.csdn.net/u/20071106/17/c562631f-fd24-4836-9e13-43c53157bd8c.html

首先感谢大家的关注和回答.但是发现大家热心有余,认真不足-------因为没有一个人真的编译过我的问题代码..
我在帖子中给的问题代码,因为去除了所有其他的不相关代码,所以是可以编译通过的.如下:
/// Matrix.h 文件内容 (部分代码)//
#include
Matrix 模板前向声明 /
template
class Matrix;
/
template
std::ostream& operator * (std::ostream& os,const Matrix & mat);/// 编译通过
template
std::ostream& operator < < (std::ostream& os,const Matrix & mat); /// /// 编译通过
template
class Matrix
{
friend std::ostream& operator * (std::ostream&,const Matrix &); /// 编译 通过
friend std::ostream& operator < < (std::ostream&,const Matrix &); /// 编译 通过
};
而我之前之所以不能编译通过,是因为我的实际代码中声明 了 一个 operator * 的重载成员函数,
导致它和友元的operator * 模板函数冲突 (但实际不应该这样啊.没看见过C++有这类语法要求.)
真正编译不通过的代码如下:
/// Matrix.h 文件内容 (这段代码编译不通过)//
#include
Matrix 模板前向声明 /
template
class Matrix;
/
template
std::ostream& operator * (std::ostream& os,const Matrix & mat);/// 编译通过
template
std::ostream& operator < < (std::ostream& os,const Matrix & mat); /// /// 编译通过
template
class Matrix
{
const Matrix operator *(const Matrix&) const; 注意..这里是问题的根源!!!!!!
friend std::ostream& operator * (std::ostream&,const Matrix &); /// 编译不通过
friend std::ostream& operator < < (std::ostream&,const Matrix &); /// 编译 通过
};
昨天发现出现编译不通过的问题后,我被引入了误区,一直以为是operator * 的问题
甚至发现 operator +, operator -,operator / 都不可以.
唯独 operator < < 可以.
后来我发现如果在类中也声明一个 operator < < 的重载成员函数,那么
friend std::ostream& operator < < (std::ostream&,const Matrix &);
这一段也将编译不通过...
所以找到解决方案------ 把所有的friend 声明,都写在类的成员定义之前.代码如下:
/// Matrix.h 文件内容 ( 编译 成功!yeah)//
#include
Matrix 模板前向声明 /
template
class Matrix;
/
template
std::ostream& operator * (std::ostream& os,const Matrix & mat);/// 编译通过
template
std::ostream& operator < < (std::ostream& os,const Matrix & mat); /// /// 编译通过
template
class Matrix
{
//注意,,把所有 friend 声明都放在成员定义之前..
friend std::ostream& operator * (std::ostream&,const Matrix &); /// 编译 通过
friend std::ostream& operator < < (std::ostream&,const Matrix &); /// 编译 通过
const Matrix operator *(const Matrix&) const; 注意..这里是问题的根源!!!!!!
};
------------------------------------------------------------------------------------------------------------------------

//from EuMatrix3.h

//history 1
//关于类模板的友元函数模板
//EuVector3 operator * (const EuVector3 & rkPoint, const EuMatrix3 & rkMatrix);
// EuMatrix3 operator* (TReal fScalar, const EuMatrix3 & rkMatrix);
//参考C++ primer 类模板中的友元声明 三种情况
//here, for second
//I use dev and vc 2005, 发现vc2005支持差,只有当把这两个友元在类中的声明放置在
//其它重载运算符*的函数(eg:EuMatrix3 operator* (const EuMatrix3& rkMatrix) const等)
//前面!!!!!
//才能编译成功!
//而dev no problem!!!!!!
//参考 http://topic.csdn.net/u/20071106/17/c562631f-fd24-4836-9e13-43c53157bd8c.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值