为什么库中的此模板类在使用时会生成链接器错误?

时间:2010-06-28 20:13:18

标签: c++ visual-studio-2008 templates linker-errors

我有以下设置。 RectangleT类在库的头文件中定义。尝试在我的主应用程序中使用该类。链接时,我尝试调用的每个函数都会出错 - 除了构造函数和GetLeft / GetTop / GetRight / GetBottom - 但是 - 我在调用GetWidth / GetHeight时遇到错误。

这是我为简单的模板类所获得的代码。

namespace My2D
{
    template <typename T>
    class MY2D_API RectangleT
    {
    public:     // Construction
        RectangleT(const T left = 0, const T top = 0, const T right = 0, const T bottom = 0)
            : m_left(left)
            , m_top(top)
            , m_right(right)
            , m_bottom(bottom)
        {
        }

        RectangleT(const RectangleT<T> &source)
            : m_left(source.m_left)
            , m_top(source.m_top)
            , m_right(source.m_right)
            , m_bottom(source.m_bottom)
        {
        }

        virtual ~RectangleT(void)
        {
        }

    public:     // Getters / setters
        T GetLeft() const { return m_left; }
        T GetTop() const { return m_top; }
        T GetRight() const { return m_right; }
        T GetBottom() const { return m_bottom; }
        T GetWidth() const { return m_right - m_left; }
        T GetHeight() const { return m_bottom - m_top; }

        void SetLeft(const T value) { m_left = value; }
        void SetTop(const T value) { m_top = value; }
        void SetRight(const T value) { m_right = value; }
        void SetBottom(const T value) { m_bottom = value; }

    protected:  // Members
        T m_left;
        T m_top;
        T m_right;
        T m_bottom;
    };
}

有人有任何想法吗?!

1 个答案:

答案 0 :(得分:2)

我删除了编译器指令 MY2D_API 并尝试了您的代码,它工作正常,请参阅下文。

Windows 7,MS VS 2010

int main ()
{
  My2D::RectangleT < int > rect;

  rect.SetBottom(3);
  rect.SetLeft(3);
  rect.SetRight(8);
  rect.SetTop(8);
  return rect.GetHeight();
}