بسم الله الرحمن الرحيم,
كنت اتصفح احدى المنتديات الاجنبيه... فاحد كبار السؤلين عن المنتدى كتب في احدى برامجه هذه الفقره
#include <iostream>
using namespace std;
class CPolygon {
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};اريد منكم ان تحاولوا ان تكشفوا ما المشكله في هذا الكود, لماذا لايعمل؟!! قبل ان تكملوا القراءه
نرى انه من الواضح انwidth, height هما private في ال parent class “CPolygon” و هما مستخدمان في كلاس CTriangle وهو تشايلد كلاس. لذا من الواضح انه لن يعمل, طيب ماهو الحل؟؟!!
الحل هو استخدام ما يسمى ب protected في كلاس البيرنتس
ليصبح البرنامج لدي كالاتي:
#include <iostream>
using namespace std;
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
class CRectangle: public CPolygon {
public:
int area ()
{ return (width * height); }
};
class CTriangle: public CPolygon {
public:
int area ()
{ return (width * height / 2); }
};اذا ماهي وظيفة ال protected , تسمح فقط للchild classes بالدخول اليها بخلاف ال private التي لا تسمح لاي كلاس بالدخول اليها, فقط الكلاس نفسه.
فقط حبيت ان انبه عن هذا الموضوع حتى لا يخطئ احد المبرمجين العرب بخطأ فادح كهذا :wacko: :wacko: :wacko: