0

I have a class A which owns a template:

.h:

template <typename T>
class A
{
    public:
        A(short number);

        T* arr;
};

.cpp:

#include "A.h"

template <typename T>
A<T>::A(short number)
{
    this->arr = new T[number];
}


I have class B which inherits class A by defining its template:

.h:

#include <StatesManager.h>
#include <StateTypes.h>

class B: QWidget, public A<MyStruct>
{
    public:
        B();
};

.cpp:

B::B(): QWidget(), A<MyStruct>(5), 
{

}

What I expect is that a class B is created which inherits the properties of class A, i.e. the dynamic array of MyStruct.

Unfortunately after compiling I get the following errors:

SRect.obj:-1: error: LNK2019: external symbol reference "public: __cdecl A<struct MyStruct>::A<struct MyStruct>(short)" (??0?$StatesManager@UMyStruct@@@@QEAA@ F@Z) not resolved in function "public: __cdecl B::B(void)" (??0SRect@@QEAA@XZ)

But what still confuses me the most is why the following code (C++ senza l'uso della libreria Qt) works:

#include <iostream>

using namespace std;

struct MyStruct{
    int v1;
    bool v2;
};

template <typename T>
class A{
    public:
        A(short num){
            arr = new T[num];  
        }
        
        T* arr;
};


class B : public A<MyStruct> {
    public:
        B(): A<MyStruct>(4){
            for (int i = 0; i < 4; i++){
                arr[i].v1 = i;
                arr[i].v2 = true;
            }
        }
};

int main()
{
    B myClass;
    
    for (int i = 0; i < 4; i++){
        cout<<myClass.arr[i].v1<<endl;
        cout<<myClass.arr[i].v2<<endl <<endl;
    }

    return 0;
}

0 Answers0