函數重載和重寫的異同點:相同點:提供函數的多組變體,名稱重用簡化程式碼。不同點:作用域:重載在同一作用域,重寫在不同作用域。參數或傳回類型:重載參數類型不同,重寫允許參數類型或傳回類型不同。目的:重載擴充功能,重寫定製或覆寫父類別方法。
特性:
#include <iostream> using namespace std; // 求面积函数,重载为正方形和圆形 double area(double side) { return side * side; } double area(double radius) { return 3.14 * radius * radius; } int main() { cout << "正方形面积: " << area(5) << endl; cout << "圆形面积: " << area(3) << endl; }
特性:
#include <iostream> using namespace std; class Shape { public: virtual double area() { return 0; } }; class Rectangle : public Shape { public: double height, width; Rectangle(double height, double width) { this->height = height; this->width = width; } double area() override { return height * width; } }; class Circle : public Shape { public: double radius; Circle(double radius) { this->radius = radius; } double area() override { return 3.14 * radius * radius; } }; int main() { Rectangle rectangle(5, 3); Circle circle(3); cout << "长方形面积: " << rectangle.area() << endl; cout << "圆形面积: " << circle.area() << endl; }
相同點:
不同點:
以上是C++ 函式重載與重寫的異同分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!