1
I have a class template Set and a menu class both with their respective . cpp and . hpp, when trying to use a cluster class pointer in my Menu class I get the following error:
||=== Build: Debug in Trabalho04 (compiler: GNU GCC Compiler) ===|
obj\Debug\src\Menu.o||In function `ZN4MenuC2Ev':|
C:\Trabalho04\src\Menu.cpp|5|undefined reference to `Conjunto<int>::Conjunto()'|
obj\Debug\src\Menu.o||In function `ZN4Menu5opcaoEv':|
C:\Trabalho04\src\Menu.cpp|22|undefined reference to `Conjunto<int>::criaConjunto()'|
||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|
Set.
template <class T>
class Conjunto {
public:
Conjunto();
void criaConjunto();
virtual ~Conjunto();
private:
Conjunto<int> * conjunto;
T * elementos;
int qtd;
int tam;
};
Set.cpp
#include "Conjunto.hpp"
#include "Bibliotecas.hpp"
template <class T>
Conjunto<T>::Conjunto() {
elementos = new T[10];
qtd = 0;
tam = 10;
}
template <class T>
void Conjunto<T>::criaConjunto(){
int num;
cin >> num;
if(conjunto!=NULL) {
conjunto = NULL;
delete conjunto;
}
if(num == 0) {
conjunto = new Conjunto<int>();
} else {
conjunto = new Conjunto<int>(num);
}
}
template <class T>
Conjunto<T>::~Conjunto() {
delete [] elementos;
elementos = NULL;
}
Menu.cpp
#include "Menu.hpp"
Menu::Menu() {
conjunto = new Conjunto<int>();
}
void Menu::opcao() {
int opcao = 0;
do {
opcao = menu();
switch(opcao) {
case 1:
conjunto->criaConjunto();
break;
case 2:
//Sair
break;
}
} while(opcao != 2);
}
Menu.hpp
#include "Conjunto.hpp"
class Menu {
public:
Menu();
int menu();
void opcao();
virtual ~Menu();
//private:
int tam;
Conjunto<int> * conjunto;
};
I understood your answer but I’m not able to apply to my code, my error occurs here
Menu::Menu() {
 conjunto = new Conjunto<int>();
}
when trying to allocate a pointer and msm occurs if trying to create a set class object. Could explain more or give another example involving classes?– Fabricio Andrade
Moved everything in the.cpp Set to the end of the.hpp Set and added
inline
in office?– Guilherme Bernal
Thus works perfectly, but would like to do in separate files
.cpp
and.hpp
only for learning (this is the final work of data structure), but if it is too laborious or complicated otherwise this way is great. Thanks for the tips so far.– Fabricio Andrade
@Fabricioandrade, in this case, to keep separate, need to declare each function passing the types you will use at the end of yours . cpp, such as my last example in the answer.
– Guilherme Bernal