如何定义模板类的朋友模板功能

时间:2017-01-06 16:50:16

标签: friend-function template-function

我有一个模板类linear search TEMPLATE.h,它是一个通用数组和一个模板函数arrayTemplate.h,它被声明为类getArraySize()的朋友,所以它可以使用类的成员函数a和类的数据成员 #ifndef arrayTemplate #define arrayTemplate #include"linear search TEMPLATE.h" #include<iostream> using namespace std; template <class T> class array_T { private: T *a; int arraySize; public : friend void linearSearch(array_T object); array_T(int s) { arraySize = s; a = new T[arraySize]; for (int i= 0; i < arraySize; ++i) { a[i] = 0; } } ~array_T() { delete[]a; } void setArray() { for (int i=0; i < arraySize; ++i) { cout << "Enter the elements of the array " << endl; cin >> a[i]; } } void getArray() { for (int i=0; i < arraySize; ++i) { cout << a[i] << endl; } } int getArraySize() { return arraySize; } }; #endif 这是一个动态分配数组

arrayTemplate.h

#include"arrayTemplate.h"
#include<iostream>
using namespace std;

template <class T>
//void linearSearch(T desiredData, int arraySize, T *elemnts) {
void linearSearch(array_T<T> object , T desiredData) {
    int arraySize = object.getArraySize();
    int loc = -1;
    int i = 0;
    for (i = 0; i < arraySize; ++i) {

        if (object.a[i] == desiredData) {
            loc = i;
            break;
        }
    }

    if (loc > 0) {
        cout << "the Item is found at position " << i + 1 << endl;
    }
    else {
        cout << "the item is not found ";
    }

}

线性搜索TEMPLATE.h

  #include"arrayTemplate.h"
   #include"linear search TEMPLATE.h"
    #include<iostream>
    using namespace std;



int main() {

    array_T<int> myArray(7);
    myArray.setArray();

    linearSearch(myArray,50)

return 0 ; 
}

的main.cpp

from collections import defaultdict

def saving_multiple_scores():
    with open(class_number, 'r') as f: # don't use file
          data = defaultdict(list)
          for line in f:
              line = line.strip() 
              if not line:
                  continue # skip over any blank lines in the file
              key, value = line.split(':')
              data[key.strip()].append(value.strip())
              # file.write removed because we don't write in readmode

    with open(class_number, 'a') as f:
        # using 'a' mode will append the score lists
        # to the end of the file
        # to overwrite the file completely, use 'w'
        for key, value in data.items():
            line = '%s:%s\n' % (key, ','.join(value),)
            f.write(line)
            print '%s' % line,

这些是我得到的错误

  

线性搜索template.h(8):错误C2065:&#39; array_T&#39;:未声明   标识符

     

线性搜索template.h(8):错误C2065:&#39;对象&#39;:未声明   标识符

     

线性搜索template.h(8):错误C2275:&#39; T&#39;:非法使用此   输入表达式

     

线性搜索template.h(6):注意:请参阅&#39; T&#39;

的声明      

线性搜索template.h(8):错误C2146:语法错误:缺少&#39;)&#39;   在标识符&#39; desiredData&#39;

之前      

main.cpp(14):错误C2660:&#39; linearSearch&#39;:功能不需要2   参数

     

==========构建:0成功,1失败,0最新,0跳过==========

0 个答案:

没有答案