C++ 为什么我对friend函数有一个未定义的引用?
在我目前的编程课程中,我们正在编写一个程序来创建任意大小的随机填充数组。必须对包含数组的类进行模板化,以便可以使用int值或char值填充数组C++ 为什么我对friend函数有一个未定义的引用?,c++,templates,undefined-reference,template-classes,C++,Templates,Undefined Reference,Template Classes,在我目前的编程课程中,我们正在编写一个程序来创建任意大小的随机填充数组。必须对包含数组的类进行模板化,以便可以使用int值或char值填充数组 此时,我所要做的就是打印出SafeArray对象,这样我就可以确保我的代码正常工作。不幸的是,我在重载的流插入操作符上不断得到一个未定义的引用错误在友好性声明和实际方法签名之间的常量差异 友好宣言: 模板 friend ostream&operator您将运算符函数定义放在哪里?@user0042在SafeArray.cpp中,它应该在main中吗?或者
此时,我所要做的就是打印出SafeArray对象,这样我就可以确保我的代码正常工作。不幸的是,我在重载的流插入操作符上不断得到一个未定义的引用错误在友好性声明和实际方法签名之间的常量差异 友好宣言: 模板
friend ostream&operator您将运算符函数定义放在哪里?@user0042在SafeArray.cpp中,它应该在main中吗?或者我需要在类标题中定义它吗?可能重复
#include <iostream>
#include <cassert>
#include <typeinfo>
#include <cstdlib>
#include <ctime>
using namespace std;
template <class T>
class SafeArray
{
private:
T* pArr;
int size;
void create(int);
public:
SafeArray();
SafeArray(int);
SafeArray(const SafeArray<T> &);
~SafeArray();
SafeArray& operator=(const SafeArray<T> &);
SafeArray operator+(SafeArray<T> &);
SafeArray operator-(SafeArray<T> &);
int& operator[](int);
SafeArray& operator++();
SafeArray operator++(int);
int getSize() {return size; }
template <class U>
friend ostream& operator<<(ostream&, SafeArray<U> &);
template <class V>
friend istream& operator>>(istream&, SafeArray<V> &);
};
template <class T>
ostream& operator<<(ostream& out, const SafeArray<T> & arr)
{
for (int i = 0; i < arr.size; i++)
{
out << arr[i] << " ";
}
return out;
}
#include "SafeArray.h"
#include <iostream>
using namespace std;
int main()
{
SafeArray<int> Safe(8);
cout << Safe;
return 0;
}