C++ 类模板示例

版权声明:版权所有 如有侵权 概不追究 https://blog.csdn.net/weixin_40903417/article/details/88068481

#include "stdafx.h"
using namespace std;

struct Student
{
    int id;
    double gpa;
};
template<class T>
class Store
{
public:
    Store();
    T &getElem();
    void putElem(const T &x);
private:
    T item;
    bool haveValue;
};
template<class T>
Store<T>::Store()
{
    haveValue=false;
}
template<class T>
T& Store<T>::getElem()
{
    if (haveValue)
    {
        return item;
    }
    else
    {
        cout<<"ERROR!"<<endl;
        exit(1);
    }
}
template<class T>
void Store<T>::putElem(const T &x)
{
    haveValue=true;
    item=x;
}
int main()
{
    Store<int> s1,s2;
    s1.putElem(1);
    s2.putElem(2);
    cout<<s1.getElem()<<" "<<s2.getElem()<<endl;
    Student a={1003,3.73};
    Store<Student> s3;
    s3.putElem(a);
    cout<<s3.getElem().gpa<<endl;
    system("Pause");
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/weixin_40903417/article/details/88068481