2015-02-10 68 views
0

我剛剛在C++中學習模板。但即使我在課程中做了所有事情,我也會犯3個錯誤。使用模板...我的代碼出了什麼問題?

這是的main.cpp:

#include <iostream> 
#include "szablony.h" 

using namespace std; 

int main() 
{ 
    cout << nmax<int>(55,402) << endl; 

    Klasa<double> a1; 
    a1.ustaw(25.54); 

    Klasa<double> a2; 
    a2.ustaw(44.55); 

    cout << a1.podaj() << " :max: " << a2.podaj() << " = " << 
    nmax<Klasa>(a1.podaj(),a2.podaj()) << endl; 

} 

這是「szablony.h」:

#include <iostream> 

using namespace std; 

template <typename T> class Klasa 
{ 
    T wartosc; 

public: 

    template <typename U> T podaj() 
    { 
     return (this -> wartosc); 
    } 

    template <typename U> void ustaw(U war) 
    { 
     wartosc=war; 
    } 
}; 

template <typename T, typename T1, typename T2> T nmax(T1 n1, T2 n2) 
{ 
    return (n1 > n2 ? n1 : n2); 
} 

template <> Klasa nmax<Klasa>(Klasa n1, Klasa n2) 
{ 
    return (n1.podaj() > n2.podaj() ? n1 : n2); 
} 

因此,這些都是錯誤:

  1. 「szablony.h」:|第27行|錯誤:無效使用o f模板名'Klasa'沒有參數列表|

  2. main.cpp | line 16 | error:沒有匹配函數調用'Klasa :: podaj()'|

  3. main.cpp |第17行錯誤:沒有用於調用'Klasa :: podaj()'的匹配函數|

這當然是從2004年順便說一句,這可能是一個原因,但即使是當我看到在互聯網上,似乎一切都OK了...

預先感謝您:)

+2

不要把'使用namespace'條款中的頭文件。 – PaulMcKenzie 2015-02-10 22:59:43

+0

在模板類中放置嵌套模板'template '(再次請不要習慣使用'namespace std;') – 2015-02-10 23:02:50

回答

1

主要問題是Klasa是一個模板類,但在nmax的專業化中作爲常規類使用它。具體而言,Klasa不代表一種類型,但例如, Klasa<int>呢。

因此,要麼讓你的函數返回一個模板的模板,或者使用Klasa<type>

相關問題