类模板中使用重载输出运算符<< VS2019编译器提示无法解析的外部命令

类模板中使用重载输出运算符<< 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;
}
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值