- Examples
In this lesson, we will look at a few examples of class templates.
We'll cover the following...
Example 1
Press + to interact
// templateClassTemplate.cpp#include <iostream>class Account{public:explicit Account(double amount=0.0): balance(amount){}void deposit(double amount){balance+= amount;}void withdraw(double amount){balance-= amount;}double getBalance() const{return balance;}private:double balance;};template <typename T, int N>class Array{public:Array()= default;int getSize() const;private:T elem[N];};template <typename T, int N>int Array<T,N>::getSize() const {return N;}int main(){std::cout << std::endl;Array<double,10> doubleArray;std::cout << "doubleArray.getSize(): " << doubleArray.getSize() << std::endl;Array<Account,1000> accountArray;std::cout << "accountArray.getSize(): " << accountArray.getSize() << std::endl;std::cout << std::endl;}
Explanation
-
We created two
Array
class objects, i.e.,doubleArray
andaccountArray
in lines 45 and 48. -
By calling the generic function
getSize()
in line 37, we can access the size of ...
Access this course and 1400+ top-rated courses and projects.