对局部结构构造函数的未定义引用



我有以下代码:

    template<typename T>
    void addGeneric(const T & val) { 
        struct Item 
        { 
            Item();
             T & value; 
            ~Item(); 
        }; 
        Item* item = new Item; // Error appear on this line
        item->value = val; 
        void* ptr = item;
        array.push_back(ptr);
    };

,我得到以下错误:

错误:未定义引用' void GenericArray::addGeneric(std::string const&)::Item::Item()'

我不明白为什么我得到它,或者我该如何解决它。

因为您实际上没有定义它们,您只是声明了构造函数和析构函数,但您没有实现/定义它们。

无论如何,您的示例可以不使用构造函数/析构函数;-)

template<typename T>
void addGeneric(const T & val) { 
    struct Item 
    { 
        Item(){
             /* do something constructive here...or simply ommit the entire constructor */
         }
         T & value; 
        ~Item(){
              /* destroy what you have created! ...or simply ommit the entire destructor too */
        } 
    }; 
    Item* item = new Item; // Error appear on this line
    item->value = val; 
    void* ptr = item;
    array.push_back(ptr);
};

最新更新