zoukankan      html  css  js  c++  java
  • c++:类模板

    #include<iostream>
    #include<cstdlib>
    using namespace std;
    struct Student{
    	int id;
    	float gpa;
    };
    template<class T>
    class Store{
    private:
    	T item;
    	int haveValue;
    public:
    	Store(void);
    	T getElem(void);
    	void putElem(T x);
    };
    template <class T>
    Store <T>::Store(void) :haveValue(0){}
    template <class T>
    T Store<T>::getElem(void)
    {
    	if (haveValue == 0){
    		cout << "no item present!" << endl;
    		exit(1);
    	}
    	return item;
    }
    template<class T>
    void Store<T>::putElem(T x)
    {
    	haveValue++;
    	item = x;
    }
    void main()
    {
    	Student g = { 1000, 23.0};
    	Store<int>S1, S2;
    	Store<Student>S3;
    	Store<double>D;
    	S1.putElem(3);
    	S2.putElem(-7);
    	cout << S1.getElem() << "," << S2.getElem() << endl;
    	S3.putElem(g);
    	cout << "the student id is:" << S3.getElem().id << endl;
    	cout << "object D:";
    	cout << D.getElem() << endl;
    }

  • 相关阅读:
    虚拟机virtualBox
    在scala命令行中加入类库
    使用git submodule
    Julia1.x安装
    texshop 使用技巧
    vimdiff换行
    双系统磁盘挂载失败
    www.wolframalpha.com
    sublime3激活方法
    实验数据
  • 原文地址:https://www.cnblogs.com/javafly/p/6037241.html
Copyright © 2011-2022 走看看