【问题标题】:C++ Inherit class with template member function带有模板成员函数的 C++ 继承类
【发布时间】:2013-06-27 17:50:33
【问题描述】:

我在编写资源类时遇到问题:

class BaseResource {
protected:
    unsigned int size;

public:
    virtual ~BaseResource() {}
    template<class T> const T& GetValue() const;
    template<class T, class U> void GetValue(const U& rhs);

    unsigned int GetSize() {
        return this->size;
    }
    void SetSize(unsigned int size) {
        this->size = size;
    }
};

template<class T>
class Resource : public BaseResource {
    T value;

public:
    virtual ~Resource() {}      
    Resource(unsigned int size, const T& rhs) { this->size = size; this->value = rhs; }

    const T& GetValue() const {return value;}
    void SetValue(const T& rhs) {value=rhs;}  
};

我认为上面的类定义正确,所以我 不明白为什么下面的代码会产生链接器错误:

Test.obj : error LNK2001: unresolved external symbol ""public: char * const & __thiscall BaseResource::GetValue(void)const " (??$GetValue@PAD@BaseResource@@QBEABQADXZ)"。

char* c = new char[3];
c[0] = '1';
c[1] = '2';
c[2] = '3';
BaseResource* resource = new Resource<char*>(3, c);
char* loadedResource = resource->GetValue<char*>();

在我看来,这应该创建一个包含 char* 并可以返回它的 Resource 实例。

谁能告诉我我在哪里犯了这个错误?

【问题讨论】:

    标签: c++ templates inheritance visual-studio-2012 resources


    【解决方案1】:

    以下方法未实现:

    template<class T> const T& GetValue() const;
    template<class T, class U> void GetValue(const U& rhs);
    

    我希望您不打算将它们虚拟化,因为那样行不通。 模板方法不能被虚拟化。 因为它们没有被实现,所以可以肯定地解释链接问题。

    【讨论】:

      【解决方案2】:

      这些函数的实现应该和类在同一个头文件中。在这种情况下,您已经实例化了模板函数,并且没有定义具体的实例化函数。每当您使用模板时,您都需要在使用该功能的翻译单元中包含该功能的定义。

      编辑


      这是基本理念。您需要定义植入,以便在实例化类时完全定义类。

      public:
          virtual ~BaseResource() {}
          template<class T> const T& GetValue() const
          {
             return someT;
          }
          template<class T, class U> void GetValue(const U& rhs)
          {
             return someT;
          } 
      
          unsigned int GetSize() {
              return this->size;
          }
          void SetSize(unsigned int size) {
              this->size = size;
          }
      };
      

      【讨论】:

      • 嗯好吧,这似乎合乎逻辑。那么你能明确告诉我如何解决所示情况的问题吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-15
      • 1970-01-01
      • 2013-05-07
      相关资源
      最近更新 更多