我的代碼:
#include <iostream>
using std::cin;
using std::cout;
using std::istream;
using std::ostream;
template<typename T>
class Complex
{
T real, img;
public:
Complex():real(0), img(0){}
friend istream& operator>>(istream& input, Complex& c1);
friend ostream& operator<<(ostream& output, Complex& c1);
Complex operator (Complex& c1);
};
template<typename T>
istream& operator>>(istream& input, Complex<T>& c1)
{
cout<<"Real: ";
input>>c1.real;
cout<<"Imag: ";
input>>c1.img;
return input;
}
template<typename T>
ostream& operator<<(ostream& output, Complex<T>& c1)
{
output<<c1.real<<" "<<c1.img<<"i";
return output;
}
template<typename T>
Complex<T> Complex<T>::operator (Complex<T>& c1)
{
Complex temp;
temp.real = this->real c1.real;
temp.img = this->img c1.img;
return temp;
}
int main()
{
Complex<int> cmp1;
cin>>cmp1;
return 0;
}
我得到的錯誤cin>>cmp1是undefined reference to 'operator>>(std::istream&, Complex<int>&)'。但我在我的代碼中找不到任何錯誤。
如果我使復雜的非模板類使用 double 并洗掉所有與模板相關的代碼,則該代碼有效,因此定義operator>>() 本質上是正確的。
Complex制作模板時會發生什么變化?
uj5u.com熱心網友回復:
Friend 函式不是成員,因此它們不是隱式模板。那里的宣告表明存在用于實體化型別的非模板運算子Complex<int>。您可以使用
template<typename U>
friend istream& operator>>(istream& input, Complex<U>& c1);
template<typename U>
friend ostream& operator<<(ostream& output, Complex<U>& c1);
uj5u.com熱心網友回復:
問題是目前多載的友元函式是普通函式。如果您想將它們作為函式模板,則需要將類中的朋友宣告更改為如下所示。
更正式地說,在您的原始代碼中operator<<和operator>>for 類模板Complex<>不是函式模板,而是在需要時使用類模板實體化的“普通”函式。也就是說,它們是模板物體。
有兩種方法可以解決這個問題,下面給出了這兩種方法。
解決方案 1
template<typename T>
class Complex
{
//other members as before
//friend declarations
template<typename U>
friend istream& operator>>(istream& input, Complex<U>& c1);
template<typename V>
friend ostream& operator<<(ostream& output, Complex<V>& c1);
//other members as before
};
演示
解決方案 2
//forward declarations
template<typename T>
class Complex;
template<typename U>
istream& operator>>(istream& input, Complex<U>& c1);
template<typename V>
ostream& operator<<(ostream& output,const Complex<V>& c1);
template<typename T>
class Complex
{
T real, img;
public:
Complex():real(0), img(0){}
//friend declarations
friend istream& operator>> <T>(istream& input, Complex<T>& c1);
friend ostream& operator<< <T>(ostream& output,const Complex<T>& c1);
Complex operator (Complex& c1);
};
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/447270.html
