c++ - 类模板中的重载运算符> friend

标签 c++ templates operator-overloading friend-function

我正试图在我的模板类中有一个重载的 operator> 友元函数。此重载运算符的目标是确定左数组是否大于右数组,而与类型无关。我想要类似 arrayInt > arrayFloat 的东西来返回一个 bool 值。但是,在定义 friend 函数时,我收到一条错误消息,提示我有一个未声明的标识符。我在 Mac 上使用 XCode。知道如何在仍然使用友元重载函数的同时解决这个问题吗?

数组.h

#ifndef Array_h
#define Array_h

#include <iostream>

template <class T> class Array;

template <class T, class S>
bool operator> (const Array<T>& arr1, const Array<S>& arr2);

template <class T>
class Array {
private:
   int arraySize;
   T * array;

public:
   Array() : arraySize(0), array(nullptr){};
   Array(int);
  ~Array();
   int getSize(){return this->arraySize;}
   void printArray();

   //error here, "S is an undeclared identifier"
   friend bool operator> (const Array<T>& arr1, const Array<S>& arr2) {
     return (arr1.arraySize > arr2.arraySize);
   }   
};

template <class T>
Array<T>::Array(int size) {
  this->arraySize = (size > 0 ? size : 0);
  this->array = new T [this->arraySize];
  for(int i=0; i<this->arraySize; i++) {
     this->array[i] = 0;
  }
}

template <class T>
Array<T>::~Array() {
  delete [] this->array;
}

template <class T>
void Array<T>::printArray() {
   for(int i=0; i<this->arraySize; i++) {
      std::cout << this->array[i] << std::endl;
   }
}

#endif /* Array_h */

主要.cpp

#include "Array.h"
int main(int argc, char ** argv) {
  Array<int> arrayInt(5);
  Array<float> arrayFloat(10);

  std::cout << "Number of elements in integer array: " << arrayInt.getSize() 
  << std::endl;
  std::cout << "Values in integer array:" << std::endl;
  arrayInt.printArray();

  std::cout << "Number of elements in float array: " << arrayFloat.getSize() 
  << std::endl;
  std::cout << "Values in float array:" << std::endl;
  arrayFloat.printArray();

  bool isGreater = arrayInt > arrayFloat;

  std::cout << isGreater;

  return 0;
}

最佳答案

friend 声明不匹配函数模板,它也必须是一个模板:

template<typename TT, typename TS> friend bool
operator >(const Array<TT>& arr1, const Array<TS>& arr2) {
  return (arr1.arraySize > arr2.arraySize);
} 

其实不用交 friend ,在外面定义,调用getSize()即可:

template<typename T, typename S> bool
operator >(const Array<T>& arr1, const Array<S>& arr2) {
  return (arr1.getSize() > arr2.getSize());
} 

关于c++ - 类模板中的重载运算符> friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47967762/

相关文章:

c++ - 提升ptree : Adding more nodes with same name and attributes

c++ - 为两个相似的类定义一次成员函数?

scala - 重载复合运算符,例如 +=

c++ - 如何测量低延迟 C++ 应用程序的延迟

c++ - 一个 'friend of a Class' 的函数允许 'read access' 到它的 'private members' 但不是 'write access' ?

c++ - 消除可变类层次结构中无参数函数调用的歧义

c++ - 有没有办法为 std::array 创建函数模板特化

函数调用运算符的 C++ 模板

C++ 得到一个我不熟悉的 "symbols not found"错误

c++ - 依赖范围和嵌套模板