|
写正题之前,先给出几个关键字的中英文对照,重载(overload),覆盖(override),隐藏(hide)。在早期的C++书籍中,可能翻译的人不熟悉专业用语(也不能怪他们,他们不是搞计算机编程的,他们是英语专业的),常常把重载(overload)和覆盖(override)搞错!
#include <iostream>
using namespace std; class Base { public: void foo(int) { cout << "Base::foo(int)" << endl; } }; class Derived : public Base { public: void foo(int,int) { cout << "Derived::foo(int,int)" << endl; } void test() { foo(1); } }; int main(int argc, char* argv[]) { return 0; }
class Base
{ public: void foo(int) { cout << "Base::foo(int)" << endl; } }; class Derived : public Base { public: void foo(int,int) { cout << "Derived::foo(int,int)" << endl; } void test() { Base::foo(1); } }; 2)使用using 声明把Base类域中的函数foo进入Derived类域
class Base
{ public: void foo(int) { cout << "Base::foo(int)" << endl; } }; class Derived : public Base { public: void foo(int,int) { cout << "Derived::foo(int,int)" << endl; } using Base::foo; void test() { foo(1); } };
class Base
{ public: void foo(int) { cout << "Base::foo(int)" << endl; } }; class Derived : public Base { public: void foo(int) { cout << "Derived::foo(int,int)" << endl; } void test() { foo(1); } };
class Base
{ public: virtual void foo(int) { cout << "Base::foo(int)" << endl; } }; class Derived : public Base { public: virtual void foo(int) { cout << "Derived::foo(int,int)" << endl; } void test() { foo(1); } };
这种情况我们叫覆盖(override)!覆盖指的是派生类的虚拟函数覆盖了基类的同名且参数相同的函数!
#include <iostream>
using namespace std; class Base { public: virtual void foo(int) { cout << "Base::foo(int)" << endl; } }; class Derived : public Base { public: vitual void foo(int,int) { cout << "Derived::foo(int,int)" << endl; } void test() { foo(1); } }; int main(int argc, char* argv[]) { return 0; } 编译出错了, |
转载::谈C++继承中的重载、覆盖和隐藏
2007-08-29 18:30
相关文章: