c++ - 在 C++ 中从模板类派生非模板类时的问题

标签 c++ inheritance sfml template-classes g++-4.7

<分区>

我正在尝试从指定我需要的女巫类型的模板类继承非模板类​​

我的代码是这样的:

基类的头文件(已更新):

//base.hpp
template<typename T>
class Base {
public:
    Base(T a,int b) :
            aa(b) {
        this->bb = a;
        // ... some code
    }
    // .. some functions ( all are NOT virtual )
protected:
    const int aa;
    T bb;
    // .. some non-constant variables
}

派生类的头文件和代码:

//derived.hpp
#include <SFML/System.hpp>
#iclude "base.hpp"

class Derived: public Base<sf::Vector2i> {
public:
    Derived(float, int, Vector2i);
    // .. other methods
protected:
    // .. other variables
}

//derived.cpp
#include "derived.hpp"

Derived::Derived(float initf, int myint, Vector2i vec) :
        Base(vec, myint) {
    // ... some codes
}

“sf”指的是与 SFML 库一起使用的 namespace 。我正在使用使用 cmake 从源代码编译的 SFML 2.0

(更多信息您可以查看:http://www.sfml-dev.org/)

当我尝试使用类似这样的命令编译这些代码时:

$ g++ ./main.cpp ./derived.cpp ./base.cpp -lsfml-system

我收到一些链接器错误,告诉我:

In function `Derived::Derived(float, int, sf::Vector2<int>)':
undefined reference to `Base<sf::Vector2<int> >::Base(sf::Vector2<int>, int)'

我还使用“g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3”作为启用了 C++11 的 C++ 编译器。

最佳答案

如果您希望编译器隐式实例化您的模板(99.9% 的情况),编译器必须查看成员的定义。将 Base 构造函数的定义移动到 header ,这应该可以解决您的问题。

关于c++ - 在 C++ 中从模板类派生非模板类时的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17497347/

相关文章:

c++ - 为什么在c++中实现基于类的优先级队列时需要重载operator<?

C++ 方法重载 : base and derived parameters

c++ - Tilemap 碰撞 SFML C++

c++ - 加法运算符没有影响

c++ - 用于运行测试和浏览报告的 Eclipse (CDT) 插件

sql - 类表继承模型的 INSERT 语句

python - 如何从子类调用基类的 __init__ 方法?

c++ - 在 SFML 中随机放置矩形

c++ - SFML TCP 套接字发送导致滞后峰值

c++ - 从传递给模板函数的内部类实例中提取外部类类型