学习C++ primer 之路 - ( 第十四章之 模板类 )

19 篇文章 0 订阅

类模板的作用基本上和函数模板差不多,主要是为了省事和减少不必要的重复的代码,比如定义一个类 其私有数据是整型但是呢,你可能会需要用到double类型数据,但是类的成员函数基本上作用一样,这时候你就需要用到类模板,首先 定义类模板

template<Class T>    //定义类模板

.

后面紧跟着是定义的类

template<Class T>
class A {
    private:
        T a;
    public:
        A(const ai):a(ai) {}
        A(const A & ai):(a = ai.a) {}
        void printfOn() const;
};

后面是实现类的成员方法

每一个方法前面都必须要有一行模板定义

template<Class T>
void A<T>::printfOn() const {
    std::cout << a << std::endl;
}

A<T> 表示类模板定义

重点: 不能将类模板成员函数放在独立的实现文件中 必须与类一起

          当类成员函数指定返回类型或使用作用域解析运算符时,必须使用完整的A<T>

          例如:

template<Class T>
class A {
    private:
        T a;
    public:
        A(const ai):a(ai) {}
        A(const A & ai):(a = ai.a) {}
        void printfOn() const;
        A & operator=(const A & a);        //有返回类型和运算符时
};
//  当类成员函数指定返回类型或使用作用域解析运算符时,必须使用完整的A<T>

template<Class T>
A<T> & A<T>::operator=(const A<T> & a) {
    a = a.a;
    return *this;
}

使用 指针特别注意 例如指针栈 它压入栈中的只是一个指向字符串的地址 并且构造函数需要动态创建内存大小,在析构函数中释放内存.

二.

另一种定义方式 

array<array<int,5>,10>  //使模板递归,相当于array[10][5] 二维数组
template<Class T,int n>   
template<Class T=int>        //表示T的类型为默认值 int类型     
template <class T,int n>
class ArrayTp {
private:
	T ar[n];
public:
	ArrayTp() {};
	explicit ArrayTp(const T & v);
	virtual T & operator[](int i);
	virtual T  operator[](int i) const;
};


template <class T, int n>
ArrayTp<T, n>::ArrayTp(const T & v) {
	for (int i = 0; i < n; i++) {
		ar[i] = v;
	}
}
template <class T, int n>
T & ArrayTp<T, n>::operator[](int i) {
	if (i < 0 || i >= n) {
		std::cerr << "Error in array limits: " << i <<
			" is out range\n";
		std::exit(EXIT_FAILURE);
	}
	return ar[i];
}
template <class T, int n>
T ArrayTp<T, n>::operator[](int i) const {
	if (i < 0 || i >= n) {
		std::cerr << "Error in array limits: " << i <<
			" is out range\n";
		std::exit(EXIT_FAILURE);
	}
	return ar[i];
}

int main() {
	using namespace std;
	ArrayTp<int, 10> sums;
	ArrayTp<double, 10> aves;
	ArrayTp<ArrayTp<int, 5>, 10>twodee;
	int i, j;
	for (i = 0; i < 10; i++) {
		sums[i] = 0;
		for (j = 0; j < 5; j++) {
			twodee[i][j] = (i + 1) * (j + 1);
			sums[i] += twodee[i][j];
		}
		aves[i] = (double)sums[i] / 10;
	}
	for (i = 0; i < 10; i++) {
		for (j = 0; j < 5; j++) {
			cout.width(2);
			cout << twodee[i][j] << ' ';
		}
		cout << ": sum = ";
		cout.width(3);
		cout << sums[i] << ", average = " << aves[i] << endl;
	}
	cout << "Done.\n";


	system("pause");
	return 0;
}

template<int,2>a1;

template<int>a1(2); 调用构造函数(这是最常见的方法)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值