C++编程思想 第1卷 第16章 模板介绍 模板语法 非内联函数的定义

当然,有时我们希望有非内联成员函数的定义
这时编译器需要在成员函数定义之前看到template声明

//: C16:Array2.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Non-inline template definition
#include "../require.h"

template<class T>
class Array {
  enum { size = 100 };
  T A[size];
public:
  T& operator[](int index);
};

template<class T>
T& Array<T>::operator[](int index) {
  require(index >= 0 && index < size,
    "Index out of range");
  return A[index];
}

int main() {
  Array<float> fa;
  fa[0] = 1.414;
  getchar();
} ///:~

引用模板的类名的地方,必须伴有该模板的参数列表,例如在Array<T>::
operator[]中

猜你喜欢

转载自blog.csdn.net/eyetired/article/details/81427602