【发布时间】:2012-10-15 16:51:26
【问题描述】:
我有以下代码:
#include <iostream>
#include <stdio.h>
using namespace std;
template <class F>
struct CMPLX {
F Re, Im;
struct _printnice {
F Re, Im;
string sep;
_printnice(const F& Re, const F& Im, const string& sep) : Re(Re), Im(Im), sep(sep) {}
};
CMPLX <F> (F Re, F Im) : Re(Re), Im(Im) {}
_printnice PrintNice(const string& sep="\t"){
return _printnice(Re, Im, sep);
}
};
template<class F>
ostream& operator << (ostream& os, const CMPLX<F> c){
cout << c.Re << " + " << c.Im << "i";
}
template<class F>
ostream& operator << (ostream& os, const CMPLX<F> :: _printnice p){
cout << p.Re << p.sep << p.Im;
}
int main(){
CMPLX<float> c(2.0,1.0);
cout << c << endl;
cout << c.PrintNice() << endl;
}
我引入了一个子结构 _printnice 以重载运算符 << 并具有我的 CMPLX 类的不同格式的输出。但是,这会引发错误
在“p”之前应该是 unqualified-id,我不知道如何解决这个问题(我对模板的了解非常有限)。
我尝试将<< 的第二个定义更改为以下有效,但我必须指定类型,这是不受欢迎的:
ostream& operator << (ostream& os, const CMPLX <float> :: _printnice p){
cout << p.Re << p.sep << p.Im;
}
【问题讨论】: