2016-04-06 20 views
-1

這是我寫的用於開始使用類模板的代碼。如何調用此類程序中涉及類模板的單參數構造函數?

#include<iostream> 
using namespace std; 
template<class T> 
class Complex 
{ 
T *real,*imag; 
public: 
    Complex(T a) 
    { 
    real=new T; 
    imag=new T; 
     *real=a; 
     *imag=0; 
    } 
    Complex(T a,T b) 
    { 
    real=new T; 
    imag=new T; 
     *real=a; 
     *imag=b; 
    } 
    Complex() 
    { 
    real=new T; 
    imag=new T; 
     *real=0; 
     *imag=0; 
    } 
template<class R>  
friend ostream& operator<<(ostream &out,Complex<R> &C); 
template<class R> 
friend istream& operator>>(istream &in,Complex<R> &C); 
template<class R> 
friend Complex<R> operator +(Complex<R> a,Complex<R> b);  
}; 
template<class R> 
ostream& operator<<(ostream &out,Complex<R> &C) 
    { 
    out<<"The number is "<<*C.real<<"+"<<*C.imag<<"i"<<endl; 
    return out; 
    } 
template<class R>  
istream& operator>>(istream &in,Complex<R> &C) 
    { 
    cout<<"Enter the number "; 
    in>>*C.real>>*C.imag; 
    return in; 
    } 
template<class R>  
Complex<R> operator +(Complex<R> a,Complex<R> b) 
{ 
Complex<R> temp; 
*temp.real=*a.real+*b.real; 
*temp.imag=*a.imag+*b.imag; 
return temp;  
}  
int main() 
{ 
Complex<float> C1,C2(4.2,6.8),C3,C4; 
C1=5; 
C3=3+C1; 
C4=C2+C3; 
cout<<C1; 
cout<<C2; 
cout<<C3; 
cout<<C4; 
} 

這段代碼一切正常,除非我嘗試使用像'3 + C2'這樣的整數值時它顯示錯誤。如果在沒有使用'3 + C2'的模板的情況下考慮相同的代碼,則調用朋友函數操作符+(複雜a,複合b),將3複製到調用單個參數構造函數的對象a,將3分配給複雜的類。如何使用類模板時發生同樣的情況?如何在使用類模板時將數字傳遞給operator +()函數而不是Complex對象時調用單參數構造函數?

+0

@πάνταῥεῖ錯誤出現在+運算符函數中。導致錯誤的整數值導致錯誤,因爲單參數構造函數未被調用。我需要知道如何在使用類模板時使用C2 = 3 + C1。謝謝 – hcoder

+2

你的代碼從骨頭上是有嚴重缺陷的。停止使用原始指針,新手入門。 –

+0

您應該刪除大部分代碼,並從'T real,imag;'重新開始。從長遠來看,這將節省大量時間。 –

回答

1

隨着像

template<class R> 
Complex<R> operator +(Complex<R>, Complex<R>); 

類型R從每個函數參數獨立地推導出兩個演繹都必須成功,並且推導出的類型必須匹配才能使用。由於3不是Complex,因此扣除失敗並且不考慮過載。

有兩種方法可以解決這個問題。一種是使用非模板友:

template<class T> 
class Complex { 
    // ... 
    friend Complex operator+(Complex a, Complex b) { 
     // ... 
    } 
}; 

這個實例爲一個非模板友元函數,這是很樂意考慮隱式轉換。

另一種方法是提供其推斷只來自一個參數附加重載:

template<class T> struct identity { using type = T; }; 
template<class T> using nondeduced_t = typename identity<T>::type; 

template<class R> 
Complex<R> operator +(nondeduced_t<Complex<R>>, Complex<R>) { /* ... */ } 

template<class R> 
Complex<R> operator +(Complex<R>, nondeduced_t<Complex<R>>) { /* ... */ } 

這是通過std::basic_string_view採取的方法。


順便說一下,您的實施已嚴重破碎。它像沒有明天一樣會泄漏內存 - 並且沒有理由首先動態分配T

+0

所以我們最終將string_view標準化了嗎?我不知道! – SergeyA

+1

@SergeyA它是已經被合併到C++ 17中的基礎V1的一部分。 –

相關問題