Answer the question
In order to leave comments, you need to log in
How to fix error: "LNK 2019 reference to unresolved symbol" c++?
Good day, I ran into this problem:
I use only three files so far:
1.RandomAccess.cpp - the main file with the main function
2.unit.h - the header file of the template class unit
3.unit.cpp - the executable file of the template class unit
RandomAccess structure .cpp
#include <iostream>
#include "unit.h"
using namespace std;
void main() {
setlocale(0, "");
unit <int> nBlock;
}
#pragma once
#include <iostream>
using namespace std;
template <typename type>
class unit{
template <typename type>
friend istream& operator >>(istream&, unit<type>&);
template <typename type>
friend ostream& operator <<(ostream&, unit<type>&);
public:
unit();
unit(int);
int size();
type& operator[] (int);
private:
int s;
type* ptr;
void to_null();
};
#include "unit.h"
#include <iostream>
#include <iomanip>
using namespace std;
#include <cstdlib>
// constructors
template <typename type>
unit<type>::unit() {
s = 16;
ptr = new type[16];
to_null();
}
template <typename type>
unit<type>::unit(int cap) {
s = (cap > 0) ? cap : 16;
ptr = new type[s];
to_null();
}
// operators
template <typename type>
type& unit<type>::operator[](int ix) {
if (ix < 0 || ix > s) {
cerr << "\n Ошибка индексации: индекс(" << ix << ") не пренадлежит этому юниту..";
exit(1);
}
else return ptr[ix];
}
template<typename type>
istream& operator>>(istream& input, unit<type>& obj) {
for (int i = 0; i < obj.size(); i++) {
input >> obj[i];
}
return input;
}
template <typename type>
ostream& operator <<(ostream& output, unit<type>& obj) {
output << "[";
int edge = obj.size();
for (int ix = 0; ix < edge; ix++) {
output << obj[ix];
if (ix + 1 != edge) output << setw(5);
}
output << "]";
return output;
}
// public functions
template <typename type>
int unit<type>::size() {
return s;
}
// private functions
template <typename type>
void unit<type>::to_null() {
for (int ix = 0; ix < s; ix++) {
ptr[ix] = 0;
}
}
Answer the question
In order to leave comments, you need to log in
The implementation of the template class must be in the *.h file.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question