在类模板中,利用友元函数重载输出运算符 << 时,不加命名空间std会报错,不加 <T> 也会报错

类的头文件:Vector0.h

#pragma once
#include <iostream>

//using namespace std;

template <typename T>
class Vector0
{
	
public:

	Vector0(int size = 0);
	Vector0(const Vector0<T> &other);
	~Vector0(void);

	Vector0& operator=(const Vector0<T> &other);
	T& operator[](int index);

	int getCount();

	template <typename T>
	friend std::ostream &operator<< <T>(std::ostream &os, const Vector0<T> &vec);
private:
	T *mem; //指向该类型数组的指针
	int count; //数组里面有多少成员
};

template <typename T>
std::ostream& operator<<(std::ostream &os, const Vector0<T> &vec);

类的实现文件:Vector0.cpp

#include <iostream>
#include "Vector0.h"

//using namespace std;

template <typename T>
Vector0<T>::Vector0(int size) {
	if(size > 0){
		count = size;
		mem = new T[count];
	}
}

template <typename T>
Vector0<T>::Vector0(const Vector0<T> &other) {
	//根据传入对象的数组数量分配内存空间
	count = other.count;
	mem = new T[count];

	//传入对象的数组
	for(int i=0; i < count; i++) {
		mem[i] = other.mem[i];
	}
}

template <typename T>
Vector0<T>::~Vector0(void) {
	if(mem) {
		delete[] mem;
		mem = NULL;
		count = 0;
	}
}

template <typename T>
Vector0<T>& Vector0<T>::operator=(const Vector0<T> &other){
	if(mem) {
		delete[] mem;
		mem = NULL;
		count = 0;
	}
	//根据传入对象的数组数量分配内存空间
	count = other.count;
	mem = new T[count];

	//传入对象的数组
	for(int i=0; i < count; i++) {
		mem[i] = other.mem[i];
	}

	return *this;
}

template <typename T>
T& Vector0<T>::operator[](int index){
	return mem[index];
}

template <typename T>
int Vector0<T>::getCount(){
	return count;
}

template <typename T>
std::ostream& operator<<(std::ostream &os, const Vector0<T> &vec) {
	for(int i=0; i<vec.count; i++) {
		os << vec.mem[i] << " ";
	}
	os << std::endl;
	return os;
}

主函数入口:main.cpp

#include <iostream>
#include <string>
#include <Windows.h>
#include "Vector0.h"
#include "Vector0.cpp"

//using namespace std;

int main(void) {
	Vector0<int> myVector(10);
	for(int i=0; i < myVector.getCount(); i++) {
		myVector[i] = i;
	}
	std::cout << myVector[i] << std::endl;
	
	system("pause");
	return 0;
}

生成一下,就会出现这种错误:
在这里插入图片描述
在加了using namespace std;之后,就没有错误了!!!
输出为:
在这里插入图片描述
【注意】:
此时,类的头文件中,友元函数这样声明:

friend std::ostream &operator<< <T>(std::ostream &os, const Vector0<T> &vec);

就是在 operator<< 后面加上 <T>
这样写是为了避免编译器报错!

不过在我不加 <T>,这样写时:

friend std::ostream &operator<<(std::ostream &os, const Vector0<T> &vec);

编译器没报这个错误,正常运行!!!
不知道为啥?有人这样写就报错了!
出现这样的报错:fatal error LNK1120: 1个无法解析的外部命令

加上 <T>之后,就不报错了!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值