2013-04-12 54 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)了解更多信息。 –

相关问题