2013-04-12 56 views
1
template <class Type> 
class Punct { 

protected: 

    Type _x; // (1) 
    Type _y; // (1) 

public: 

    Punct(Type = 0, Type = 0); // (2) 
    ~Punct(); 
    inline Type getX() const { return _x; } 
    inline Type getY() const { return _y; } 

    inline void setX(Type x) { _x = x; } 
    inline void setY(Type y) { _y = y; } 
    inline void moveBy(int x, int y) { _x = x; _y = y; } 

friend std::istream &operator>>(std::istream&ins, Punct<Type>& A); 
friend std::ostream &operator<<(std::ostream&outs, const Punct<Type>& A); 

}; 

這是我得到的錯誤:場具有不完整的類型

(1) - 場具有不完全類型 '類型'

(2) - 沒有可行的從int類型轉換(有的加3.把參數傳給參數)

你能告訴我,我做錯了什麼?

+0

該代碼沒有意義。 'Type'是一個類型,而不是一個變量,所以你不能給它賦值。你的意思是在你的構造函數中添加一個變量名。向我們展示'Type'的定義。 –

+1

@EdS .:它不是賦值,它是初始化。 –

+0

@Teodora:它取決於你實例化的類型。 **顯示代碼** –

回答

1

此代碼適用於我。 g++ 4.7.2Kubuntu 12.04上。

順便說一句,您是否已將Punct類的所有實現都集成在一個文件中,即頭文件中,或者將它們分隔爲.h和,?

#include <iostream> 
using namespace std; 

template <class Type> 
class Punct { 

protected: 

    Type _x; // (1) 
    Type _y; // (1) 

public: 

    Punct(Type = 0, Type = 0) {}; // (2) <- empty function body added 
    ~Punct() {}; // <- empty function body added 
    inline Type getX() const { return _x; } 
    inline Type getY() const { return _y; } 

    inline void setX(Type x) { _x = x; } 
    inline void setY(Type y) { _y = y; } 
    inline void moveBy(int x, int y) { _x = x; _y = y; } 

    template<class T> // <- added 
    friend std::istream &operator>>(std::istream&ins, Punct<T>& A); 
    template<class T> // <- added 
    friend std::ostream &operator<<(std::ostream&outs, const Punct<Type>& A); 

}; 

// bogus function added 
template<class T> 
istream &operator>> (istream &i, Punct<T> &a) 
{ 
    return i; 
} 

// bogus function added 
template<typename T> 
ostream &operator<< (ostream &i, const Punct<T>& a) 
{ 
    return i; 
} 

int main() 
{ 
    Punct<int> a; 
} 
+0

是的,我已經在.cpp文件中實現了非內聯函數,爲什麼? – Teodora

+1

@Teodora對於模板類,通常所有的實現都在頭文件中。如果不是,則需要付出很多努力。看到這個職位:http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – gongzhitaao

+1

@Teodora:模板化類必須完全定義(實施)在頭文件。這種限制是由於聯繫的方式而產生的。閱讀[這個問題](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file)瞭解更多信息。 –

相關問題