您的位置:首页 > 编程语言 > C语言/C++

C++函数重定义、重载、重写

2010-09-20 07:23 260 查看
              C++函数重定义、重载、重写

1. 重写 (override):

父类与子类之间的多态性。子类重新定义父类中有相同名称和参数的虚函数。

1) 被重写的函数不能是 static 的。必须是 virtual 的 ( 即函数在最原始的基类中被声明为 virtual ) 。

2) 重写函数必须有相同的类型,名称和参数列表 (即相同的函数原型)

3) 重写函数的访问修饰符可以不同。尽管 virtual 是 private 的,派生类中重写改写为 public,protected 也是可以的

2. 重载 (overload):

指函数名相同,但是它的参数表列个数或顺序,类型不同。但是不能靠返回类型来判断。

3. 重定义 (redefining):

子类重新定义父类中有相同名称的非虚函数 ( 参数列表可以不同 ) 。

重写与重载的区别 (override) PK (overload)

1、方法的重写是子类和父类之间的关系,是垂直关系;方法的重载是同一个类中方法之间的关 系,是水平关系。

2、重写要求参数列表相同;重载要求参数列表不同。

3、重写关系中,调用那个方法体,是根据对象的类型(对象对应存储空间类型)来决定;重载关系,是根据调用时的实参表与形参表来选择方法体的。

class Base

{

private:

virtual void display() { cout<<"Base display()"<<endl; }

void say(){ cout<<"Base say()"<<endl; }

public:

void exec(){ display(); say(); }

void f1(string a) { cout<<"Base f1(string)"<<endl; }

void f1(int a) { cout<<"Base f1(int)"<<endl; } //overload

};

class DeriveA:public Base

{

public:

void display() { cout<<"DeriveA display()"<<endl; } //override

void f1(int a,int b) { cout<<"DeriveA f1(int,int)"<<endl; } //redefining

void say() { cout<<"DeriveA say()"<<endl; } //redefining

};

class DeriveB:public Base

{

public:

void f1(int a) { cout<<"DeriveB f1(int)"<<endl; } //redefining

};

int main()

{

DeriveA a;

Base *b=&a;

b->exec(); //display():version of DeriveA call(polymorphism)

//say():version of Base called(allways )

a.exec(); //same result as last statement

a.say();

//a.f1(1); //error:no matching function, hidden !!

DeriveB c;

c.f1(1); //version of DeriveB called

}

注意:在 C++ 中若基类中有一个函数名被重载,在子类中重定义该函数,则基类的所有 版本将被隐藏——即子类只能用子类定义的,基类的不再可用。——名字隐藏特性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: