overload-override-hide 的区别

来源:互联网 发布:免费服务器安全软件 编辑:程序博客网 时间:2024/06/03 00:31

下面是我参考C++国际标准文档 《C++ Standard - ANSI ISO IEC 14882 2003》查找到的关于

 

overload-override-hide 的一些区别,希望可以供大家参考!:)

 


1. overload:
two declarations in the same scope that declare the same name but with different types are called
overloaded declarations.
在同一范围内两个定义名字相同,但是类型不同,被称为 overload 定义

Only function declarations can be overloaded; object and type declarations cannot be overloaded.
只有函数定义可以被 overload; 对象和类型定义不能被overload

// example 1
void f (int i, int j);
void f ();        // OK: overloaded declaration of f

void f (int i, int j = 99);  // OK: redeclaration of f(int, int)
void f (int i = 88, int j);  // OK: redeclaration of f(int, int)

///////////////////////////////////////////
2. override:

// example 1
struct B
{
 virtual void f(int);
 virtual void f(char);
 void g(int);
 void h(int);
};
struct D : public B
{
 void f(int);      // OK: D::f(int) overrides B::f(int);
 void g(char);     // OK
 void h(int);      // OK: D::h(int) hides B::h(int)
};

// example 2
struct Base
{
 virtual void vf1();
 virtual void vf2();
 virtual void vf3();
 void f();
};
struct Derived : public Base
{
 void vf1();      // virtual and overrides Base::vf1()
 void vf2(int);     // not virtual, hides Base::vf2()
 char vf3();   // error: invalid difference in return type only
 void f();
};


////////////////
3. Any assignment operator, even the copy assignment operator, can be virtual.

// example 1
struct B
{
 virtual int operator= (int)
 {
  cout << "B : int operator= (int)... " << endl;
  return 0;
 }
};
struct D : public B
{
 virtual int operator= (int)
 {
  cout << "D : int operator= (int)... " << endl;
  return 0;
 }
};

int main(void)
{
 B *p = new D;
 p->operator =(20); // call D::operator= (int)

 return 0;
}

 

 

原创粉丝点击