【发布时间】:2010-05-26 05:48:37
【问题描述】:
我有一门课:
template<class T>
class matrix
{
private:
int COLS,ROWS;
public:
inline matrix(int r,int c){
this->COLS=r;
this->ROWS=c;
}
template<class T2>
friend ostream& info(ostream& os);
};
我尝试了很多方法来实现信息功能。但没有一个成功。
我想在主函数中使用它
Matrix<int> M(10,20);
cout<<info<<M;
我想输出 Matrix 类的列和行信息。
我在实现朋友类信息方面尝试了很多次,但都失败了。
谁能告诉我怎么做?
对不起,我忘了放
template<class T2>
friend ostream& operator<< (ostream &out,matrix<T2> &cMatrix);
实施:
template<class T2>
ostream & operator<<(ostream &out, matrix<T2> &cMatrix) {
out<<cMatrix.getCOLS();// sorry for didn't put the get function, it's not easy to put code line by line here.
out<<cMatrix.getROWS();
return out;
}
我的
但是当我想使用信息时,我得到了错误。
我不确定,如何将自己的类型操纵器实现为友元函数。 我谷歌了一些,但它们不是朋友功能。而且,它是一种模板 功能。
这就是我想要的:
template<class T2>
ostream& info(ostream& os,matrix<T2> &cMatrix)
{
int cols=cMatrix.getCOLS();
int rows=cMatrix.getROWS();
os<<rols<<"X"<<rows<<" matrix "<<endl;
return os;
}
【问题讨论】:
-
别忘了正确缩进你的源代码。
-
为什么需要使用机械手?免费或成员函数会容易得多。另一种选择是使用proxy class。
-
主持人,我正在努力完成我的一项任务。老师让我们练习机械手的东西。所以,他让我把这个作为必要的功能来实现。
标签: c++ formatting iostream