symphonyenigmatic Thành viên bậc 3
Tổng số bài gửi : 61 Points : 104 Reputation : 6 Join date : 26/07/2009 Age : 35 Đến từ : http:://thienthancntt.tk
| Tiêu đề: Ép kiểu cho con trỏ trong kế thừa Sun Aug 02, 2009 6:07 pm | |
| Thằng con kế thừa từ thằng cha, nhưng mà thằng cha lại không thể dùng con trỏ để truy nhập đến thằng con. Muốn điều đó xảy ra, thì phải ép con trỏ. Code về ép con trỏ như sau File diem.h - Code:
-
http://diem.h//dinh nghia lop Diem #ifndef DIEM_H #define DIEM_H class Diem { protected: float x,y; public: Diem (float a=0, float b=0); void THDiem(float a, float b); float TDoX() const { return x; } float TDoY() const { return y; } friend ostream & operator << (ostream & out, const Diem &p); }; #endif File diem.cpp - Code:
-
//diem.cpp //Dih nghia cac ham thanh vien cua lop Diem #include <iostream.h> #include "diem.h"
Diem::Diem(float a, float b) { THDiem(a,b); }
void Diem::THDiem(float a, float b) { x = a; y = b; }
ostream & operator <<(ostream &out, const Diem &p) { out << '[' << p.x << ", " << p.y << ']'; return out; }
File Duongtron.h - Code:
-
http://duongtron.h//dinh nghia lop duongtron #ifndef DUONGTRON_H #define DUONGTRON_H #include "diem.h" class DuongTron : public Diem { protected: float bankinh; public: DuongTron(float r=0.0, float a=0, float b=0); void KTBK(float r); float LayBK() const; float DienTich() const; friend ostream & operator <<(ostream & Output, const DuongTron &C); }; #endif File duongtron.cpp - Code:
-
//duongtron.cpp //Dinh nghia cac ham thanh vien cua lop BanKinh.cpp #include <iostream.h> #include <iomanip.h> #include "duongtron.h"
DuongTron::DuongTron(float r, float a, float b): Diem(a, b) { bankinh = r; }
void DuongTron::KTBK(float r) { bankinh = r; }
float DuongTron::LayBK() const { return bankinh; }
float DuongTron::DienTich() const { return 3.14159 * bankinh * bankinh; }
//Xuat duongtron theo dang: ToaDoTam = [x, y]; Bankinh = #.## ostream & operator <<(ostream &Output, const DuongTron &C) { Output << "Toa Do Tam = [" << C.x << ", " << C.y << "]; Ban Kinh = " << setiosflags(ios::showpoint) << setprecision(2) << C.bankinh; return Output; }
File thihanh.cpp - Code:
-
//Chuong trinh thi hanh //Ep cac con tro lop co so toi con tro lop dan xuat #include <iostream.h> #include <iomanip.h> #include "diem.h" #include "diem.cpp" #include "duongtron.h" #include "duongtron.cpp"
void main() { Diem *pt, P(3.5, 5.3); DuongTron *cp, C(2.7, 1.2, 8.9); cout << "Diem P: "<<P<<endl<<"Duong Tron C: "<<C<< endl; //Xu ly 1 duong tron nhu 1 diem, chi xem 1 phan lop co so pt = &C; cout << endl << "Duong Tron C (va *pt): "<<*pt<<endl; pt = &C; cp = (DuongTron *) pt; cout << endl << endl <<*cp<< endl << cp->DienTich() << endl; pt = &P; cp = (DuongTron *) pt; cout << endl <<*cp<< endl <<cp->DienTich() << endl; }
| |
|