首頁  >  文章  >  後端開發  >  C++ 函式重載和重寫的理解和使用

C++ 函式重載和重寫的理解和使用

王林
王林原創
2024-04-20 15:36:011029瀏覽

C 中函數重載允許在同一類別中定義同名函數,但參數列表不同;函數重寫發生在子類別中定義一個與父類別同名且參數相同的函數,子類別函數將覆蓋父類別函數。在實戰範例中,重載函數用於針對不同資料類型執行加法運算,重寫函數用於覆蓋父類別中的虛擬函數,以計算不同形狀的面積。

C++ 函数重载和重写的理解和使用

C 函數重載與重寫:深入理解與實戰應用

函數重載

函數重載允許在同一類別中定義擁有相同函數名稱但參數清單不同的多個函數。

class MyClass {
public:
  int add(int a, int b);
  double add(double a, double b);
};

int MyClass::add(int a, int b) {
  return a + b;
}

double MyClass::add(double a, double b) {
  return a + b;
}

函數重寫

函數重寫發生在子類別中定義一個與父類別同名且具有相同參數清單的函數時。子類別函數將覆蓋父類別函數。

class ParentClass {
public:
  virtual int display() {
    return 10;
  }
};

class ChildClass : public ParentClass {
public:
  int display() { // 重写父类的 display()
    return 20;
  }
};

實戰案例

重載函數範例:

#include <iostream>

class Calculator {
public:
  int add(int a, int b) {
    return a + b;
  }

  double add(double a, double b) {
    return a + b;
  }

  std::string add(std::string a, std::string b) {
    return a + b;
  }
};

int main() {
  Calculator calc;
  std::cout << calc.add(1, 2) << std::endl;   // 输出:3
  std::cout << calc.add(1.5, 2.5) << std::endl; // 输出:4
  std::cout << calc.add("Hello", "World") << std::endl; // 输出:HelloWorld
  return 0;
}

重寫函數範例:

#include <iostream>

class Shape {
public:
  virtual double area() = 0; // 纯虚函数(强制子类实现 area())
};

class Rectangle : public Shape {
public:
  Rectangle(double width, double height) : m_width(width), m_height(height) {}
  double area() override {
    return m_width * m_height;
  }

private:
  double m_width;
  double m_height;
};

class Circle : public Shape {
public:
  Circle(double radius) : m_radius(radius) {}
  double area() override {
    return 3.14 * m_radius * m_radius;
  }

private:
  double m_radius;
};

int main() {
  Rectangle rect(5, 10);
  Circle circle(5);
  std::cout << "Rectangle area: " << rect.area() << std::endl; // 输出:50
  std::cout << "Circle area: " << circle.area() << std::endl; // 输出:78.5
  return 0;
}

以上是C++ 函式重載和重寫的理解和使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn