Menu
CoddyTech

מתודות וירטואליות ו־override

שיעור 38 מתוך 48 בקורס C# למפתחי C++ של Coddy.

גם C++ וגם C# משתמשות בשליחה וירטואלית, אבל העתקת ערכים ב-C++ עלולה לחתוך אובייקט נגזר כשהוא מוקצה לערך מטיפוס בסיס. הפניות למחלקות ב-C# מונעות את אותה תבנית חיתוך. ב-C# נדרש להשתמש ב-override ולא רק בחתימה תואמת, והסתרת איבר באמצעות new היא פעולה שונה.

אפשר לדרוס איברים וירטואליים במחלקה נגזרת. override שומר על שליחה פולימורפית דרך הפניה מטיפוס בסיס; הסתרת איבר באמצעות new היא פעולה שונה. בנאי של מחלקה נגזרת יכול לקרוא ל-base כדי לאתחל מצב משותף. יש להשתמש בירושה רק כשהטיפוס הנגזר עומד בחוזה של מחלקת הבסיס.

דוגמה ב-C++

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
class Plan { protected: int unit; public: explicit Plan(int n):unit(n) {} virtual int total(int n) const { return unit*n; } virtual ~Plan()=default; };
class DiscountPlan: public Plan { public: explicit DiscountPlan(int n):Plan(n) {} int total(int n) const override { return Plan::total(n)*9/10; } };
int main() {
DiscountPlan concrete(10); Plan& plan=concrete; cout << plan.total(2) << "\n";
}

הצהרות עזר ב-C#

class Message { public virtual string Speak() { return "hello"; } }
class LoudMessage : Message { public override string Speak() { return base.Speak().ToUpperInvariant(); } }

פקודות בתוך Main ב-C#

Message message = new LoudMessage();
Console.WriteLine(message.Speak());

אלה קטעים ממוקדים לצורכי הוראה. קובצי האתגר כוללים מעטפות מלאות שניתנות להרצה; הקטעים שלמעלה מציגים את ההצהרות והפקודות הרלוונטיות.

פלט לדוגמה:

18

פלט ב-C#:

HELLO
challenge icon

אתגר

קל

השלם את Plan.Total ואת DiscountPlan.Total. התמחור הבסיסי הוא unit * count. ‏DiscountPlan מחזירה את הרצפה של 90 אחוז מהסכום הבסיסי השלם. קלטים לא שליליים שומרים על מכפלות קטנות. תוכנית הנהג קוראת דרך הפניה ל-Plan כדי לדרוש שיגור וירטואלי.

ערוך את קובצי C# שאינם נעולים. הקובץ הנעול הגלוי Main.cs קורא את השורות המתוארות, קורא ל-Exercise.Solve, מוודא שהקלט לא השתנה ומדפיס את התוצאה עם תו שורה חדשה אחד בסוף. השאר את ה-API המוצהרים. אל תוסיף Main נוסף ואל תדפיס פלט אבחוני.

המשגר הנעול גם בודק בנפרד את ה-API של פונקציית העזר או המחלקה המיוצאת, ולא רק את מעטפת Solve.

נסו בעצמכם

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
var a2 = input[2] == "true"; string before2=Snapshot(a2);
Plan p1 = new DiscountPlan(10); Plan p2 = new Plan(10); if (p1.Total(3) != 27 || p2.Total(3) != 30) throw new Exception("Virtual API");
var result = Exercise.Solve(a0,a1,a2);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
if (Snapshot(a2) != before2) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz iconבחנו את עצמכם

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

כל השיעורים ביחידה C# למפתחי C++

תרגלו בעצמכם: קומפיילר C# אונליין