C++中函数的重写和重载之间的区别
Difference between overriding and overloading of a function in C++
我正在大学学习 c plus plus 课程,我无法区分函数的覆盖和重载,任何人都可以帮助我。
以下是两种不同的foo
重载:
void foo(int);
void foo(char);
这里B::bar
是一个函数覆盖:
class A {
public:
virtual void bar();
};
class B : public A {
public:
void bar() override;
};
重
载意味着具有不同参数的同名函数,它实际上并不取决于您使用的是过程语言还是可以进行重载的面向对象语言。 就覆盖而言,这意味着我们正在显式定义一个存在于派生类的基类中的函数.显然,您需要面向对象的语言来执行覆盖,因为它是在基类和派生类之间完成的。
重载意味着在同一作用域中声明多个具有相同名称的函数。它们必须具有不同的参数类型,并且在编译时根据参数的静态类型选择合适的重载。
void f(int);
void f(double);
f(42); // selects the "int" overload
f(42.0); // selects the "double" overload
重写意味着派生类声明与基类中声明的虚函数匹配的函数。 通过指针或对基类的引用调用函数将根据对象的动态类型在运行时选择重写。
struct Base {
virtual void f();
};
struct Derived : Base {
void f() override; // overrides Base::f
};
Base * b = new Base; // dynamic type is Base
Base * d = new Derived; // dynamic type is Derived
b->f(); // selects Base::f
d->f(); // selects Derived::f
覆盖意味着,给出具有相同参数的现有函数的不同定义,重载意味着使用不同的参数添加现有函数的不同定义。
例:
#include <iostream>
class base{
public:
virtual void show(){std::cout<<"I am base";} //this needs to be virtual to be overridden in derived class
void show(int x){std::cout<<"nI am overloaded";} //this is overloaded function of the previous one
};
class derived:public base{
public:
void show(){std::cout<<"I am derived";} //the base version of this function is being overridden
};
int main(){
base* b;
derived d;
b=&d;
b->show(); //this will call the derived version
b->show(6); // this will call the base overloaded function
}
输出:
I am derived
I am overloaded
相关文章:
- 构造函数和转换运算符之间的重载解析
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 你能帮我了解重载一元运算符和二进制运算符之间的区别吗?
- 将重载构造函数传递给类之间的函数
- C++模板和非模板函数之间的重载解析
- C++ 类的构造函数和函数调用运算符 () 重载之间的歧义
- 函数隐藏和重载之间的区别
- 模板流运算符重载错误:引用初始化无效,与basic_istream和basic_ifstream之间的差异有关
- Int64 和 time_t 之间的 C++ 重载歧义
- 函数重载和双精度和长之间的混淆
- 基类和派生类中的模板成员之间的重载解析
- 如何在两个不同的类之间重载"=="运算符?
- 派生类 插入和提取运算符重载以及基类与派生类之间的强制转换
- 模板专用类之间的构造函数重载
- C++ 中多态性和函数重载之间的区别
- 指针之间的运算符重载
- ostream 插入运算符与其非成员重载之间的关系
- C++中函数的重写和重载之间的区别
- 函数重载和方法重载之间的区别
- 在不同的运算符=重载之间,编译似乎没有遵循正确的路径