文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>what is overloading and overiddin..

what is overloading and overiddin..

时间:2010-09-29  来源:Caterjava

In C++, overriding is a concept used in inheritance which involves a base class implementation of a method. Then in a subclass, you would make another implementation of the method. This is overriding. Here is a simple example.

class Base
{
public:
virtual void DoSomething() {x = x + 5;}
private:
int x;
};
class Derived : public Base
{
public:
virtual void DoSomething() { y = y + 5; Base::DoSomething(); }
private:
int y;
};

Here you can see that the derived class overrides the base class method DoSomething to have its own implementation where it adds to its variable, and then invokes the parent version of the function by calling Base::DoSomething() so that the x variable gets incremented as well. The virtual keyword is used to that the class variable can figure out which version of the method to call at runtime.

Overloading is when you make multiple versions of a function. The compiler figures out which function to call by either 1) The different parameters the function takes, or 2) the return type of the function. If you use the same function declaration, then you will get a compiler error because it will not know which function to use. Here is another simple example.

class SomeClass
{
public:
void SomeFunction(int &x) { x *= x; }
int SomeFunction(int x) { return x * x; }
};

// In main()
SomeClass s;
int x = 5;
x = SomeFunction(x);

The compiler knows to call the second implementation of the method because we are assigning the return value from the function to x.

相关阅读 更多 +
排行榜 更多 +
超级冒险王安卓版

超级冒险王安卓版

休闲益智 下载
玩具小镇手机版

玩具小镇手机版

休闲益智 下载
这一关特上头手机版

这一关特上头手机版

休闲益智 下载