在类模板中,利用友元函数重载输出运算符 << 时,不加命名空间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>之后,就不报错了!

猜你喜欢

转载自blog.csdn.net/weixin_46060711/article/details/124564940