C++模板学习-个人练习

 

//函数模板的写法
template <typename T>  
//定义类型标示
T abs(T val){
	return val<0 ? -val : val;
}
#include <iostream>
//类模板的写法
template <class Type> class MyBinaryTree{
public:
	MyBinaryTree();
	MyBinaryTree(Type a, MyBinaryTree *b, MyBinaryTree *c, int high = 0);
	//定义默认值要在声明出给出默认值
	int getHeight(void);
	void setContent(Type);
	Type getContent(void);
private:
	MyBinaryTree * left;
	MyBinaryTree * right;
	Type content;int height;
};

template <class Type>MyBinaryTree<Type>::MyBinaryTree(){
	left = NULL;
	right = NULL;
	height = 1;
}
template <class Type>  //MyBinaryTree<Type>前要加上这个前缀
MyBinaryTree<Type>::MyBinaryTree(Type val, MyBinaryTree *lt, MyBinaryTree *rt, int high){
	content = val;
	left = lt;
	right = rt;
	height = high;
}

template <class Type>
void MyBinaryTree<Type>::setContent(Type val){
	content = val;
}

template <class Type>
Type MyBinaryTree<Type>::getContent(){
	return content;
}

template <class Type>
int MyBinaryTree<Type>::getHeight(){
	return height;
}

void printX(int t = 0){
	printf("%d/n", t);
}

int main(){
	MyBinaryTree<int> bt;
	bt.setContent(5);
	std::cout<<bt.getContent()<<std::endl;
	std::cout<<bt.getHeight()<<std::endl;
	MyBinaryTree<double> dt(3.5, 0, 0);
	std::cout<<dt.getContent()<<std::endl;/**/
	printX(1);
	printX();
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值