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.
转载于:https://blog.51cto.com/ymbian/399137