a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 46|回复: 0

[C++] 理解C++编译器编译模板类的过程(1)

[复制链接]
发表于 2012-7-31 21:56:58 | 显示全部楼层 |阅读模式
  前言
) s0 l6 T, a: G( c  常遇到询问使用模板到底是否容易的问题,我的回答是:“模板的使用是容易的,但组织编写却不容易”。看看我们几乎每天都能遇到的模板类吧,如STL, ATL, WTL, 以及Boost的模板类,都能体会到这样的滋味:接口简单,操作复杂。
% ?. n  S7 m* ~5 K, F  本文对象是那些熟悉模板但还没有很多编写模板经验的程序员。本文只涉及模板类,未涉及模板函数。但论述的原则对于二者是一样的。. P9 o: T, m, a
  问题的产生
- g7 }2 \; c4 j% J2 V4 H2 V  通过下例来说明问题。例如在array.h文件中有模板类array:" R/ i  x  M3 b  v
  // array.h3 M) e  e! d4 I
  template
4 i/ j9 x3 S( E0 c  class array( u- y6 a( ]/ ?9 t( L' ^
  {
) i& D2 ?: R8 j3 ?; Z! u: [  T data_[SIZE];
& ~/ E; o, _) j- J% J  array (const array& other);' `" s- [3 l4 L7 Z" o  H' \
  const array& operator = (const array& other);
8 V% y( U8 g4 U4 O& l, U6 d" o  public:
! n1 ?8 v! g$ f( D  array(){};; ]6 R( z6 K' A! \& w0 l2 ~
  T& operator[](int i) {return data_;}
0 b1 T, @4 T7 S/ a  const T& get_elem (int i) const {return data_;}' K$ x" ?$ S, @+ H
  void set_elem(int i, const T& value) {data_ = value;}0 [/ U! K, g  O* L4 L" e$ J5 v
  operator T*() {return data_;}
! p0 a% }1 q- S2 w, W* _: w  };% V6 B! c" k8 \2 h- y# E% f) t
  然后在main.cpp文件中的主函数中使用上述模板:: x" k' `  \2 {; r
  // main.cpp) G( G3 F/ q. J: Z: m
  #include "array.h"( d7 ]# \& F6 W. ^/ r" o
  int main(void)& K; E7 m$ n) Z0 b' W9 a
  {
+ f# i. o9 |, ~7 ~1 k  array intArray;8 G/ A9 n2 D8 |% p0 \9 p+ d
  intArray.set_elem(0, 2);
" N; ~0 _3 f0 Z' g  int firstElem = intArray.get_elem(0);' t; s# f3 F1 T
  int* begin = intArray;3 f6 s) Q! p3 t2 j+ {& r
  }
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Woexam.Com ( 湘ICP备18023104号 )

GMT+8, 2024-6-27 00:42 , Processed in 0.284097 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表