עבור לתוכן

|C++| שאלה על function name hiding...

Featured Replies

פורסם

תקנו אותי אם אני טועה,

function name hiding זה למעשה מתן שם זהה אבל חתימה שונה (מס' ו/או סוג פרמטרים שונה) למחלקת בסיס ומחלקה נגזרת כדי שלא יפעילו בטעות פונק' של מחלקת האב מתוך מחלקה נגזרת ?

פורסם

כן.

בכל מקרה, מי שכותב קוד כזה צריך שיגררו אותו לרחוב וירו בו.

אפשר להימנע מההסתרה הזו ע"י שימוש במילה using.

פורסם
  • מחבר

בקיצור function name hiding זה רע מאוד ? או שיש דרך אחרת לעשות את זה ?

פורסם

עדיף להימנע מדברים כאלה, פשוט כי הם מועדים לפורענות. כמו שלא תגדיר שתי פונקציות עם אותו שם (וחתימה שונה) שעושות דברים שונים לחלוטין.

מה זאת אומרת "דרך אחרת לעשות את זה"? לעשות מה?

פורסם
  • מחבר

לא משנה , הבנתי שHIDING זה רע...

אני שואל כי לימדו אותנו את זה ויש לי מבחן שבוע הבא - אז רציתי לוודא את המושג הזה...

תודה ! :xyxthumbs:

פורסם

Bjarne Stroustrup's C++ Style and Technique That question (in many variations) are usually prompted by an example like this:

#include<iostream> using namespace std;

class B {

public: int f(int i) { cout << "f(int): "; return i+1; } // ...

};

class D : public B {

public: double f(double d) { cout << "f(double): "; return d+1.3; } // ...

};

int main() {

D* pd = new D; cout << pd->f(2) << '\n';

cout << pd->f(2.3) << '\n

}

which will produce: f(double): 3.3 f(double): 3.6 rather than the f(int): 3 f(double): 3.6 that some people (wrongly) guessed.

In other words, there is no overload resolution between D and B. The compiler looks into the scope of D, finds the single function "double f(double)" and calls it. It never bothers with the (enclosing) scope of B. In C++, there is no overloading across scopes - derived class scopes are not an exception to this general rule. (See

D&E or TC++PL3 for details).

But what if I want to create an overload set of all my f() functions from my base and derived class? That's easily done using a using-declaration:

class D : public B {

public: using B::f; // make every f from B available double

f(double d) { cout << "f(double): ";

return d+1.3; } // ...

};

Give that modification, the output will be f(int): 3 f(double): 3.6 That is, overload resolution was applied to B's f() and D's f() to select the most appropriate f() to call.

http://www2.research.att.com/~bs/bs_faq2.html#overloadderived

פורסם
  • מחבר

אחי לא הבנתי כלום, הכל מבולגן. יש מצב שאתה מעלה קובץ וורד עם מה שכתבת פה ?

פורסם
  • מחבר

תודה רבה !! הבנתי.

ארכיון

דיון זה הועבר לארכיון ולא ניתן להוסיף בו תגובות חדשות.

דיונים חדשים