【问题标题】:Overloaded operator> friend in class template类模板中的重载运算符>朋友
【发布时间】:2017-12-25 10:28:29
【问题描述】:

我试图在我的模板类中拥有一个重载的 operator> 友元函数。此重载运算符的目标是确定左数组是否大于右数组,而与类型无关。我想要一些类似于 arrayInt > arrayFloat 的东西来返回一个布尔值。但是,在定义朋友函数时,我收到一条错误消息,告诉我我有一个未声明的标识符。我在 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 */

main.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;
}

【问题讨论】:

  • 虽然它显然是可以修复的,但正如下面的答案所示......这是一个相当可疑的顺序关系。特别是因为它比较了所有诚实无关的类型。

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


【解决方案1】:

朋友声明与函数模板不匹配,它也必须是模板:

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

其实不用加好友,在外面定义,直接调用getSize()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 2020-11-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-08-27
    • 2021-05-18
    相关资源
    最近更新 更多