You are on page 1of 8

TRƯỜNG ĐẠI HỌC SƯ PHẠM KỸ THUẬT TP.

HCM
HCMC UNIVERSITY OF TECHNOLOGY AND EDUCATION

OBJECT ORIENTED PROGRAMMING


USING C++

GV. Trần Thị Quỳnh Như


Email: nhuttq@hcmute.edu.vn
Chapter 4. Templates

1. Introduction
2. Function Templates
3. Class Templates
4. IO stream
5. Exercises
Function Templates

template<class type>ret-type func-name(parameter list) {


//body of the function
}
#include <iostream>
using namespace std;
template <class M> M Max(M i, M j){
return (i > j) ? i : j;
}

int main(){
cout << Max<int>(5, 8) << endl;
cout << Max<double>(6.5, 4.0) << endl;
cout << Max<char>('f', 'k') << endl;
}
template <class type> class class-name {
Class Templates ………….
#include <iostream> }
#include <string>
#include <typeinfo>
using namespace std;
template <typename t> class student{
private:
string student_name;
t total_marks;
public:
student();
student(string n, t m){
student_name = n;
total_marks = m; }
void getinfo(){
cout << "STUDENT NAME: " << student_name << endl;
cout << "TOTAL MARKS: " << total_marks << endl;
cout << "Type ID: " << typeid(total_marks).name()<< endl;}};
Class Templates

int main() { int main() {


student<int> s1("Le A", 100); student<int> s1("Le A", 100);
student<double> s2("Tran B", 90.5); student<int> s2("Tran B", 90);
s1.getinfo(); s1.getinfo();
s2.getinfo(); s2.getinfo();
system("pause"); system("pause");
} }
I/O STREAM

Stream-I/O template hierarchy portion showing the main file-processing templates.


EXERCISES

• Bài 1: Viết chương trình sắp sếp các số từ nhỏ đến lớn sử dụng Function Template
• Bài 2: Viết CT máy tính đơn giản (+-*/ bình phương, căn bậc 2, ) sử dụng Class
Template
• Bài 3: Viết CT đổi đơn vị chiều dài, thể tích, diện tích, khối lượng, tốc độ
• Bài 4: Tìm hiểu Stream IO và file IO
• Bài 5: Viết chương trình mở một file có tên là iostream.txt, kiểm tra mở file thành công
hay không, nếu thành công, ghi nội dung vào file và sau đó chuyển đổi thành dạng chữ
hoa.

You might also like