函数得载 (在编译时实现)
null
它通过更改签名提供函数的多个定义,即更改参数的数量,更改参数的数据类型,返回类型不起任何作用。
- 它可以在基类和派生类中完成。
- 例子:
void area(int a);void area(int a, int b);
CPP
// CPP program to illustrate // Function Overloading #include <iostream> using namespace std; // overloaded functions void test( int ); void test( float ); void test( int , float ); int main() { int a = 5; float b = 5.5; // Overloaded functions // with different type and // number of parameters test(a); test(b); test(a, b); return 0; } // Method 1 void test( int var) { cout << "Integer number: " << var << endl; } // Method 2 void test( float var) { cout << "Float number: " << var << endl; } // Method 3 void test( int var1, float var2) { cout << "Integer number: " << var1; cout << " and float number:" << var2; } |
输出:
Integer number: 5Float number: 5.5Integer number: 5 and float number: 5.5
函数重写(在运行时实现) 它是基类函数在其派生类中的重新定义,具有相同的签名,即返回类型和参数。
- 它只能在派生类中完成。
- 例子:
Class a{public: virtual void display(){ cout << "hello"; }};Class b:public a{public: void display(){ cout << "bye";}};
CPP
// CPP program to illustrate // Function Overriding #include<iostream> using namespace std; class BaseClass { public : virtual void Display() { cout << "This is Display() method" " of BaseClass" ; } void Show() { cout << "This is Show() method " "of BaseClass" ; } }; class DerivedClass : public BaseClass { public : // Overriding method - new working of // base class's display method void Display() { cout << "This is Display() method" " of DerivedClass" ; } }; // Driver code int main() { DerivedClass dr; BaseClass &bs = dr; bs.Display(); dr.Show(); } |
输出:
This is Display() method of DerivedClassThis is Show() method of BaseClass
函数重载与函数重写:
- 继承: 当一个类从另一个类继承时,就会发生函数重写。重载可以在没有继承的情况下发生。
- 函数签名: 重载函数的函数签名必须不同,即参数的数量或类型应该不同。在重写时,函数签名必须相同。
- 职能范围: 重写的函数在不同的范围内;而重载函数在同一范围内。
- 函数的行为: 当派生类函数必须执行一些添加的或与基类函数不同的工作时,需要重写。重载用于具有相同名称的函数,这些函数的行为取决于传递给它们的参数。
本文由 马扎尔·米克 和 亚什·辛拉 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END