【问题标题】:Field has incomplete type字段类型不完整
【发布时间】:2013-04-12 20:25:09
【问题描述】:
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 到 type 没有可行的转换(有些添加 3. 在这里将参数传递给参数)

你能告诉我我做错了什么吗?

【问题讨论】:

  • 该代码毫无意义。 Type 是一个类型,而不是一个变量,所以你不能给它赋值。你的意思是在你的构造函数中添加一个变量名。告诉我们Type的定义。
  • @EdS.:这不是赋值,而是初始化。
  • @Teodora:这取决于您实例化的类型。 显示代码
  • 我得到了一些标题,作为家庭作业,我必须实现这些功能。在拳头而不是'类型'它是int。我有一个基类 Shape ,它具有派生类,如 Triangle、Square 等(一切正常,直到我开始最后一项任务是参数化类以便 Triangle 具有 int Points 等等。我是模板新手,我读了一些文章,我认为这是我应该做的。)

标签: c++ templates


【解决方案1】:

此代码对我有用。 g++ 4.7.2 Kubuntu 12.04

顺便说一句,您是否将Punct 类的所有实现都放在一个文件中,即头文件,还是将它们分成.h.cpp

#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;
}

【讨论】:

  • 是的,我在.cpp文件中实现了not inline函数,为什么?
  • @Teodora 对于模板类,通常所有实现都放在头文件中。如果没有,则需要付出很多努力。看到这个帖子:stackoverflow.com/questions/495021/…
  • @Teodora:模板化的类必须在头文件中完全定义(实现)。施加此限制是因为链接的工作方式。阅读this question了解更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
  • 2011-04-29
  • 2017-08-16
  • 2013-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多