1/21
Bài 12
CÁC KHÁI NIM NÂNG CAO
V CLASS
Hàm friend
2/21
 mt hàm không phi thành viên truy xut c
các thành viên riêng ca lp phi khai báo bng t
khóa friend.
Cn khai báo prototype ca hàm bn trong phn
public ca class. Ví d
class cl {
// ...
public:
friend void frnd(cl ob);
// ...
};
3/21
class myclass {
int a, b;
public:
myclass(int i, int j) { a=i; b=j; }
friend int sum(myclass x); // sum() is a friend of myclass
};
int sum(myclass x)
{
return x.a + x.b;
}
int main()
{
myclass n(3, 4);
cout << sum(n);
return 0;
}
Ví d
Quá ti constructor
4/21
Dùng hàm to nhng dng khác.
 quá ti hàm to ch vic khai báo dng mà nó
nhn và nh ngha mi hành ng liên h vi
nhng dng này.
Ví d
5/21
#include <ctime>
class timer{
int seconds;
public:
// seconds specified as a string
timer(char *t) { seconds = atoi(t); }
// seconds specified as integer
timer(int t) { seconds = t; }
// time specified in minutes and seconds
timer(int min, int sec) { seconds = min*60 + sec; }
void run();
} ;
void timer::run()
{
clock_t t1;
t1 = clock();
while((clock()/CLOCKS_PER_SEC - t1/CLOCKS_PER_SEC) <
seconds);
cout << "\a"; // ring the bell
}
int main()
{
timer a(10), b("20"), c(1, 10);
a.run(); // count 10 seconds
b.run(); // count 20 seconds
c.run(); // count 1 minute, 10 seconds
return 0;
}