C++ 中的函数重载 VS 覆盖
本文将介绍 C++ 中函数重载 VS 覆盖的区别。
在 C++ 中使用函数重载定义具有不同参数列表的多个函数
函数重载是 C++ 语言的特性,可以有多个同名、不同参数且位于一个作用域内的函数。通常,重载函数执行非常相似的操作,为它们定义单个函数名称并公开具有多个参数集的接口是很直观的。在本例中,我们定义了一个名为 Planet
的类,其中包含三个名为 printNumAcu
的函数。所有这些函数都有不同的参数,它们在编译时是有区别的。请注意,重载函数必须具有不同的参数类型或不同数量的参数。
#include <iostream>using std::cout; using std::cin;
using std::endl; using std::string;
class Planet {
private:
int num{};
public:
explicit Planet(int i): num(i) {}
void printNumAcu() const {
cout << num * num << endl;
}
void printNumAcu(int x) const {
cout << num * num * x << endl;
}
void printNumAcu(int x, int y) const {
cout << num * num * x * y << endl;
}
};
int main() {
Planet m1(3);
m1.printNumAcu();
m1.printNumAcu(3);
m1.printNumAcu(3, 3);
return EXIT_SUCCESS;
}
输出:
9
27
81
在 C++ 中使用函数覆盖重新定义派生类中的继承成员
函数覆盖是与派生类及其继承相关的功能。通常,派生类继承所有基类成员,有些会在派生类中重新定义以实现自定义例程。但是请注意,基类需要指定应该被覆盖的成员函数。这些成员函数被称为虚函数并且在定义中也包含关键字 virtual
。还有一个纯虚函数的概念,它是一种不需要定义的虚函数。包含或继承(不覆盖)纯虚函数的类称为抽象基类,它们通常不应用于创建对象,而是派生其他类。
#include <iostream>using std::cout; using std::cin;
using std::endl; using std::string;
class Planet {
protected:
int num{};
public:
explicit Planet(int i): num(i) {}
virtual void printName() = 0;
};
class Mars : public Planet {
public:
explicit Mars(int i) : Planet(i) {}
void printName() override {
cout << "Name's Mars " << num << endl;
}
};
class Earth : public Mars {
public:
explicit Earth(int i) : Mars(i) {}
void printName() override {
cout << "Name's Earth " << num << endl;
}
};
int main() {
Earth e1(3);
e1.printName();
Mars m1 = e1;
m1.printName();
return EXIT_SUCCESS;
}
输出:
Name's Earth 3
Name's Mars 3
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。