c++ - 模板类的链接器错误

标签 c++ templates linker-errors

我在编译模板类时遇到一个奇怪的错误。这是我的最小示例:

#include <iostream>

using namespace std;

template<class T>
class A{
        T element;
        protected:
                virtual bool empty() const noexcept = 0;

};

template<class T>
class B : public A<T> {
        public:
                bool tryOP(T &element) const {
                        if (A<T>::empty())
                                return false;
                        else
                        {
                                std::cout << "Operation" << std::endl;
                                return true;
                        }
                }
};

template <class T>
class C : public B<T> {

        private:

                bool empty() const noexcept override{
                        return true;
                }
};

int main(){
        int n = 0;
        C<int> c;
        c.tryOP(n);
}

错误:

/tmp/ccJvMBCZ.o: In function B::tryOP(int&) const: A.cpp:(.text._ZNK1BIiE5tryOPERi[_ZNK1BIiE5tryOPERi]+0x18): undefined reference to `A::empty() const' collect2: error: ld returned 1 exit status

为什么未定义对 empty() 的引用?它就在那里!

最佳答案

方法A<T>::empty()是抽象方法,所以不能调用,但是可以调用this->empty() .

关于c++ - 模板类的链接器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45263650/

相关文章:

c++ - 为什么模板只能在头文件中实现?

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

ios - 阿卡佩拉TTS引擎: "Undefined symbols" in XCode for all classes

c++ - 关于返回 const 引用的问题

c++ - SFML textEntered 无法正常工作

c++ - excev() 帮助 : can I use "./program"?

c++ - 使用模板时:错误:没有匹配的构造函数用于初始化

c++ - 无法理解这是循环依赖还是 Clang

c - 链接器错误: How can there be a duplicate symbol in just one file?

c++ - 在 C++ 中,可以从动态库中访问外部定义的全局变量吗?