LẬP TRÌNH C/C++ NÂNG CAO
Yêu cầu trước khi đọc: học xong Lập trình C/C++ căn bản
BÀI 5: TEMPLATE (TIẾP) part 2
Cuối cùng là “main.cpp”
CODE
#include "array.h"
class Person
{
int age;
public:
Person()
{
age=0;
}
Person(int age)
{
this->age=age;
}
int getAge() const
{
return age;
}
friend bool operator!=(const Person& p1,const Person& p2)
{
return p1.getAge()!=p2.getAge();
}
friend ostream& operator<<(ostream& os,const Person& p)
{
os<<p.getAge()<<endl;
yếu làm việc bằng GCC và VI trong *nix chứ không phải Window. Việc sử
dụng các bộ Visual Studio tuy không bị cấm nhưng
không được khuyến khích. Và bài tập lẫn bài thi đều phải submit nguyên
project kèm makefile để biên dịch trong môi trường *nix
hết.
Viết operator overload và copy constructor
Trong phần trước ta đã xem các ví dụ dùng cách “tham chiếu mà tham chiếu
đến con trỏ” Trong phần này chúng ta sẽ overload
toán tử = và viết copy constructor cũng sử dụng lại cách này, mà không phải
dùng đến prototype template function
CODE
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class Array
{
public:
int size;
T* elems;
Array(int);
Array(const Array<T>*&);
void setValue(const T&,int i);
T& getValue(int n);
Array<T>& operator=(const Array<T>*&);
friend bool operator!=(const Array<T>&,const Array<T>&);
};
template<typename T>
Array<T>::Array(int size)
{
return *this;
}
template<typename T>
bool operator!=(const Array<T>& a1,const Array<T>& a2)
{
if(a1.size!=a2.size) return true;
else for(int i=0;i<a1.size;i++)
if(*(a1.elems+i) == *(a2.elems+i)) return false;
return true;
}
int main()
{
Array<string> a(2);
a.setValue("hello",0);
a.setValue("world",1);
Array<string> b(3);
b = a;
cout<<b.getValue(0)<<endl;
cout<<b.getValue(1)<<endl;
return 0;
}