类模板中使用重载输出运算符<< VS2019编译器提示无法解析的外部命令
在模板类, 使用重载运算符的时候,编译器无法通过编译
后来问了大牛, 才知道是C++开发者挖的一个坑, 只要在代码里添加<>就完美解决
代码:
#pragma once
#include <iostream>
using namespace std;
//Vector容器类
template <typename T>
class Vector{
public:
Vector(int size = 64); //构造函数
Vector(const Vector& other); //拷贝构造函数
~Vector(); //析构函数
T& operator[](int index); //下标运算符
Vector& operator=(const Vector& other); //赋值运算符
int getLength() const; //获取长度
//必须加上 operator<< <>
friend ostream& operator<< <> (ostream& os, const Vector& object);
private:
T* m_data; //数据
int m_len; //长度
};
#include "Vector.h"
template<typename T>
inline Vector<T>::Vector(int len){
if (len < 0) return;
this->m_len = len;
this->m_data = new T[m_len];
}
template<typename T>
inline Vector<T>::Vector(const Vector<T>& other){
m_len = other.m_len;
m_data = new T[m_len];
for (int i = 0; i < m_len; i++) {
m_data[i] = other[i];
}
}
template<typename T>
inline Vector<T>::~Vector(){
if (m_data) {
delete[] m_data;
m_data = NULL;
m_len = 0;
}
}
template<typename T>
inline T& Vector<T>::operator[](int index) {
return this->m_data[index];
}
template<typename T>
Vector<T>& Vector<T>::operator=(const Vector<T>& other){
if (this = other) return;
if (this->m_data) {
delete m_data;
m_data = NULL;
m_len = 0;
}
m_len = other.m_len;
m_data = new T[m_len];
for (int i = 0; i < m_len; i++) {
m_data[i] = other[i];
}
return *this;
}
template<typename T>
int Vector<T>::getLength() const{
return m_len;
}
template<typename T>
//友元函数, 实现输出运算符重载
ostream& operator<< <> (ostream &os, const Vector<T>& object) {
for (int i = 0; i < object.m_len; i++) {
os << object.m_data[i] << " ";
}
return os;
}